我想要我的班级
template <class T,unsigned int n> class X;
创建一个包含n倍类型T的std ::元组.有没有一个特别整齐的方式呢?有没有一个很好的方法来做这个任意可变的模板类?
这是我先做的
#include <tuple> template <class,unsigned int,class> struct simple_repeat_helper; template <class T,unsigned int n,class... Args> struct simple_repeat_helper<T,n,std::tuple<Args...>> { typedef typename simple_repeat_helper<T,n-1,std::tuple<Args...,T>>::type type; }; template <class T,std::tuple<Args...>> { typedef std::tuple<Args...> type; }; template <class T,unsigned int n> struct simple_repeat { using type = typename simple_repeat_helper<T,std::tuple<>>::type; };
但实际上,我不需要这个std :: tuple,而是另一个类似的类.所以我以为我会创建一个更通用的版本:
template <class,template <class...> class,class> struct repeat_helper; template <class T,template <class...> class M,class... Args> struct repeat_helper<T,M,M<Args...>> { typedef M<Args...> type; }; template <class T,M<Args...>> { typedef typename repeat_helper<T,M<Args...,template <class...> class M = std::tuple> struct repeat { using type = typename repeat_helper<T,M<>>::type; };
我以为我可以这样使用:
repeat<double,5,std::tuple>::type x = std::make_tuple( 1.,2.,3.,4.,5. );
但不幸的是,由于:
ambiguous class template instantiation for ‘struct repeat_helper<double,0u,std::tuple,std::tuple<double,double,double> >’
任何关于这个错误的帮助将不胜感激!
解决方法
我会这样做:
template<typename,typename> struct append_to_type_seq { }; template<typename T,typename... Ts,template<typename...> class TT> struct append_to_type_seq<T,TT<Ts...>> { using type = TT<Ts...,T>; }; template<typename T,unsigned int N,template<typename...> class TT> struct repeat { using type = typename append_to_type_seq< T,typename repeat<T,N-1,TT>::type >::type; }; template<typename T,template<typename...> class TT> struct repeat<T,TT> { using type = TT<>; };
作为一个小考验:
#include <type_traits> #include <tuple> template<typename... Ts> struct X { }; int main() { repeat<double,std::tuple>::type t = std::make_tuple(1.,5.); static_assert( std::is_same< decltype(t),double> >::value,"!"); repeat<double,3,X>::type y; static_assert( std::is_same<decltype(y),X<double,double>>::value,"!"); }
最后一个live example.