来自元组的构造函数参数 [英] Constructor arguments from tuple

查看:40
本文介绍了来自元组的构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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); }
};

这篇关于来自元组的构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆