来自元组的构造函数参数

2021-12-13 00:00:00 constructor templates c++ c++11 stdtuple

假设我有一个模板,它由一个类类型和许多参数类型参数化.匹配这些类型的一组参数存储在一个元组中.如何将这些传递给类类型的构造函数?

Suppose I have a template which is parametrized by a class type and a number of argument types. a set of arguments matching these types are stored in a tuple. How can one pass these to a constructor of the class type?

几乎在 C++11 代码中:

In almost C++11 code:

template<typename T, typename... Args>
struct foo {
  tuple<Args...> args;
  T gen() { return T(get<0>(args), get<1>(args), ...); }
};

如何在不固定长度的情况下填充构造函数调用中的...?

How can the ... in the constructor call be filled without fixing the length?

我想我可以想出一些复杂的递归模板调用机制来做到这一点,但我不敢相信我是第一个想要这个的人,所以我想会有现成的解决方案这在那里,甚至可能在标准库中.

I guess I could come up with some complicated mechanism of recursive template calls which does this, but I can't believe that I'm the first to want this, so I guess there will be ready-to-use solutions to this out there, perhaps even in the standard libraries.

推荐答案

C++17 有 std::make_from_tuple 为此:

C++17 has std::make_from_tuple for this:

template <typename T, typename... Args>
struct foo
{
  std::tuple<Args...> args;
  T gen() { return std::make_from_tuple<T>(args); }
};

相关文章