std :: forward_as_tuple将参数传递给2个构造函数 [英] std::forward_as_tuple to pass arguments to 2 constructors
问题描述
我想传递多个参数以在函数内构造两个对象,方法与 std :: pair< T1,T2>(std :: piecewise_construct,...)
有效。
I would like to pass multiple arguments in order to construct two objects inside a function, the same way std::pair<T1, T2>(std::piecewise_construct, ...)
works.
所以我写了
template <typename Args0..., typename Args1...>
void f(std::tuple<Arg0> args0, std::tuple<Args1> args1) {
Object0 alpha(...);
Object1 beta(...);
...
}
所以我可以打电话
f(std::forward_as_tuple(..., ..., ...), std::forward_as_tuple(..., ...))
但是我不知道如何构造 Object0
和 Object1
。我已经检查了标准库的 std :: pair
的源代码,它们似乎使用复杂的内部函数来获取args0和args1的索引。您是否知道如何执行此操作?
But I don't know how to construct Object0
and Object1
. I have checked the source code of my standard library for std::pair
and they seems to use complicated internal functions to get the indices of args0 and args1. Do you have any idea on how to do that?
推荐答案
C ++ 17将具有 make_from_tuple
进行此操作,但是您可以使用C ++ 11编写。这是从 cppreference (对于C ++ 11)中盗取的C ++ 14版本您可以使用
C++17 will have make_from_tuple
for doing this, but you can write this in C++11. Here's a C++14 version stolen from cppreference (for C++11 you can use the implementation of std::index_sequence
from Implementation C++14 make_integer_sequence).
namespace detail {
template <class T, class Tuple, std::size_t... I>
constexpr T make_from_tuple_impl( Tuple&& t, std::index_sequence<I...> )
{
return T(std::get<I>(std::forward<Tuple>(t))...);
}
} // namespace detail
template <class T, class Tuple>
constexpr T make_from_tuple( Tuple&& t )
{
return detail::make_from_tuple_impl<T>(std::forward<Tuple>(t),
std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>{});
}
使用此实用程序,实现 f
轻而易举:
With this utility, the implementation of f
is a breeze:
template <typename... Args0, typename... Args1>
void f(std::tuple<Args0...> args0, std::tuple<Args1...> args1) {
auto alpha = make_from_tuple<Object0>(args0);
auto beta = make_from_tuple<Object1>(args1);
}
为了使其更通用,我建议您仅推导那些类型元组并对其进行完美转发:
To make it more generic, I'd recommend just deducing the types of those tuples and perfect-forwarding them:
template <typename T0, typename T1>
void f(T0&& args0, T1&& args1) {
auto alpha = make_from_tuple<Object0>(std::forward<T0>(args0));
auto beta = make_from_tuple<Object1>(std::forward<T1>(args1));
}
这篇关于std :: forward_as_tuple将参数传递给2个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!