简体   繁体   English

如何从可变参数模板参数创建 std::tuple<>?

[英]How do I create an std::tuple<> from a variadic template parameter?

I have a class that is declared with this template: template <typename ...Args> .我有一个用这个模板声明的类: template <typename ...Args> In it, I have a list declared as std::vector<std::tuple<Args...>> vec;在其中,我有一个声明为std::vector<std::tuple<Args...>> vec; to store data entries specified by the template.存储模板指定的数据条目。 I also have a function declared as follows:我还有一个函数声明如下:

void AddVertex(Args... data)
{
    // vec.push_back(std::tuple<Args...>(data));
}

In this function, I want to add a tuple of Args... to the vector.在这个函数中,我想向向量添加一个 Args... 元组。 Is this possible?这可能吗? I have tried using the code in the comment, but the compiler gives me an error saying that "the parameter pack must be expanded in this context".我已经尝试使用注释中的代码,但是编译器给了我一个错误,说“必须在此上下文中扩展参数包”。

This solution doesn't work, because the template argument of the tuple is already expanded.解决方案不起作用,因为元组的模板参数已经展开。

You need to expand both:您需要扩展两者:

  • template parameters pack ( Args... )模板参数包( Args...

and

  • function parameters pack ( data... ):函数参数包( data... ):

so it should be:所以应该是:

    vec.push_back(std::tuple<Args...>(data...));

Or shorter form, use make_tuple :或者更短的形式,使用make_tuple

    vec.push_back(std::make_tuple(data...));

As hinted by the compiler, you need to expand the parameter pack data , so this should work:正如编译器所暗示的,您需要扩展参数包data ,所以这应该可以工作:

void AddVertex(Args... data)
{
    vec.push_back(std::tuple<Args...>(args...));
}

Also, consider using emplace_back instead:另外,请考虑使用emplace_back代替:

void AddVertex(Args... data)
{
    vec.emplace_back(args...);
}

Both of the above functions will copy every argument and thus are not idiomatic C++.上述两个函数都将复制每个参数,因此不是惯用的 C++。 This may or may not be an issue to you.这对您来说可能是也可能不是问题。 To avoid this do something like为了避免这种情况,请执行以下操作

template <typename... T>
void AddVertex(T&&... args)
{
    vec.emplace_back(std::forward<T>(args)...);
}

which is a little more verbose, but will avoid those unnecessary copies.这有点冗长,但会避免那些不必要的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM