最近有空研究了一下C++0x相关的问题,并且在GCC4.6下用变长参数模板实现元组。
templatestruct MyTuple; template<> struct MyTuple<> {}; template struct ElementType; template struct MyTuple { MyTuple(Head h, Tail... t) : tail(t...) , head(h) { } MyTuple(const MyTuple& t) : tail(t.tail) , head(t.head) { } MyTuple(MyTuple&& t) : tail(t.tail) , head(t.head) { } MyTuple tail; Head head; typedef Head HeadType; typedef MyTuple TailType; }; //获取元组指定元素的值 template struct get_class { template static typename ElementType >::type& get(MyTuple& t ) { return get_class ::get(t.tail); } template static const typename ElementType >::type& get(const MyTuple& t ) { return get_class ::get(t.tail); } }; template <> struct get_class<0> { template static typename MyTuple::HeadType& get(MyTuple& t ) { return t.head; } template static const typename MyTuple::HeadType& get(const MyTuple& t ) { return t.head; } }; //推导元组指定元素的类型 template struct ElementType { private: typedef typename T::TailType Next; public: typedef typename ElementType ::type type; }; template struct ElementType<0, T> { typedef typename T::HeadType type; }; template < int k,typename Head, typename ... Tail> typename ElementType >::type& get(MyTuple& t) { return get_class ::get(t); } template < int k,typename Head, typename ... Tail> const typename ElementType >::type& get(const MyTuple& t) { return get_class ::get(t); }
使用方式:
MyTuplet(2.1,0,1.11,6666,"helloworld z","world"); cout << get<0>(t) << get<1>(t) << get<2>(t) << get<3>(t) << get<4>(t) << get<5>(t) << std::endl; get<0>(t) = 100; get<1>(t) = 10; get<4>(t) = "gg world"; const MyTuple tc(0,0,111.1,5555,"helloworld"); cout << get<0>(tc) << get<1>(tc) << get<2>(tc) << get<3>(tc) << get<4>(tc) << std::endl; cout << get<1>( MyTuple (3.1415926,'c')) << std::endl;