我想使用std :: tuple的所有元素作为类的初始化.有没有比元组的每个元素执行std :: get< i-th element>(std :: tuple)更简单的方法?
最小工作示例与std :: get:
#include <string> #include <tuple> #include <cassert> struct A { std::string string1; int intVal; std::string string2; }; int main() { std::tuple< std::string,int,std::string > myTuple("S1",42,"S2"); A myA{ std::get<0>(myTuple),std::get<1>(myTuple),std::get<2>(myTuple) }; assert( myA.string1 == "S1" ); assert( myA.intVal == 42 ); assert( myA.string2 == "S2" ); }
有关实例,请参见http://coliru.stacked-crooked.com/a/4a5d45dbf1461407
解决方法
正如
Kerrek SB所说,这个
P0209R0已经有了一个建议.因此,直到达到标准,你可以按照以下几点做一些事情:
template<typename C,typename T,std::size_t... I> decltype(auto) make_from_tuple_impl(T &&t,std::index_sequence<I...>) { return C{std::get<I>(std::forward<T>(t))...}; } template<typename C,typename... Args,typename Indices = std::make_index_sequence<sizeof...(Args)>> decltype(auto) make_from_tuple(std::tuple<Args...> const &t) { return make_from_tuple_impl<C>(t,Indices()); }
并将您的课程初始化为:
A myA{make_from_tuple<A>(myTuple)};
您也可以手工制作index_sequence和make_index_sequence,以便在07年3月4日提出的C 11中工作,并更改为:
namespace idx { template <std::size_t...> struct index_sequence {}; template <std::size_t N,std::size_t... Is> struct make_index_sequence : make_index_sequence<N - 1,N - 1,Is...> {}; template <std::size_t... Is> struct make_index_sequence<0u,Is...> : index_sequence<Is...> { using type = index_sequence<Is...>; }; } template<typename C,std::size_t... I> C make_from_tuple_impl(T &&t,idx::index_sequence<I...>) { return C{std::get<I>(std::forward<T>(t))...}; } template<typename C,typename Indices = idx::make_index_sequence<sizeof...(Args)>> C make_from_tuple(std::tuple<Args...> const &t) { return make_from_tuple_impl<C>(t,Indices()); }