来自元组的构造函数参数

Constructor arguments from tuple(来自元组的构造函数参数)
本文介绍了来自元组的构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)