As Kerrek SB commented there's already a proposal for this P0209R0. Consequently, until it's in the standard you could do something along these lines:
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());
}
And initialize your class as:
A myA{make_from_tuple<A>(myTuple)};
Live Demo
You could also hand-craft index_sequence
and make_index_sequence
for this to work in C++11 as proposed by Jarod42 here, and change to:
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, typename T, 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... Args, 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());
}
Live Demo