型配列
複数の型をlistに束縛してnthで取り出してみる。
中身はlispちっくにconsセルでつなげてます。
#include <iostream> #include <typeinfo> struct nil_t {}; template <typename... args> struct cons_cell; template <typename first, typename... rest> struct cons_cell<first, rest...> { typedef first car; typedef cons_cell<rest...> cdr; }; template <typename last> struct cons_cell<last> { typedef last car; typedef cons_cell<nil_t> cdr; }; template <> struct cons_cell<nil_t> { typedef cons_cell<nil_t> car; typedef cons_cell<nil_t> cdr; }; template <typename ... args> struct list; template <typename first, typename... rest> struct list<first, rest...> { typedef cons_cell<first, rest...> type; }; template <typename type_list, int number> struct nth { typedef typename nth<typename type_list::cdr, number-1>::type type; }; template <typename type_list> struct nth<type_list, 0> { typedef typename type_list::car type; }; int main() { typedef list<int, char, short, long, double, float, unsigned int>::type types_list; std::cout << typeid(types_list::cdr::car).name() << std::endl; std::cout << typeid(nth<types_list, 5>::type).name() << std::endl; std::cout << typeid(nth<types_list, 6>::type).name() << std::endl; std::cout << typeid(nth<types_list, 7>::type).name() << std::endl; std::cout << typeid(nth<types_list, 8>::type).name() << std::endl; return 0; }
で
$ g++ -g -Wall -std=c++0x -o type_list type_list.cpp
$ ./type_list | c++filt -t
char
float
unsigned int
cons_cell
cons_cell
てなかんじです。
うーん、nil_tは中にcar, cdr用意しといた方がよかったな・・・