如何将类型从可变模板参数转换为另一种类型?
例如:
template <typename... T> struct single { std::tuple<T...> m_single; }; template <typename... T> struct sequences { single<T...> get(size_t pos) { // I don't know how to convert here return std::make_tuple(std::get<0>(m_sequences)[pos]... std::get<N>(m_sequences)[pos]); } template <size_t Idx> std::vector< typename std::tuple_element<Idx,std::tuple<T...>>::type > get_sequence() { return std::get<Idx>(m_sequences); } std::tuple<T...> m_sequences; // std::tuple<std::vector<T...>> I don't know how to conver here };
我想写:
sequences<int,double,double> seq; single<int,double> sin = seq.get(10);
并且具有std :: tuple< std :: vector< int>,std :: vector< double>,std :: vector< double>>在结构序列中.并从中获得单身.
的std ::矢量<单<吨...>>对我来说是个坏主意,因为我需要一个完整的序列,并且很容易将它复制出来. 可能吗? 非常感谢你.对不起,我的英语不好.
解决方法
您可以做的不仅仅是将可变参数包作为普通列表扩展:您也可以扩展表达式.因此,您可以将m_sequences作为元素的元组,而不是元素的元组:
template <typename... T> struct sequences { std::tuple<std::vector<T>...> m_sequences; };
您还可以使用参数包进行漂亮的技巧,从矢量中选择适当的元素:
template<size_t ... Indices> struct indices_holder {}; template<size_t index_to_add,typename Indices=indices_holder<> > struct make_indices_impl; template<size_t index_to_add,size_t...existing_indices> struct make_indices_impl<index_to_add,indices_holder<existing_indices...> > { typedef typename make_indices_impl< index_to_add-1,indices_holder<index_to_add-1,existing_indices...> >::type type; }; template<size_t... existing_indices> struct make_indices_impl<0,indices_holder<existing_indices...> > { typedef indices_holder<existing_indices...> type; }; template<size_t max_index> typename make_indices_impl<max_index>::type make_indices() { return typename make_indices_impl<max_index>::type(); } template <typename... T> struct sequences { std::tuple<std::vector<T>...> m_sequences; template<size_t... Indices> std::tuple<T...> get_impl(size_t pos,indices_holder<Indices...>) { return std::make_tuple(std::get<Indices>(m_sequences)[pos]...); } std::tuple<T...> get(size_t pos) { return get_impl(pos,make_indices<sizeof...(T)>()); } };