可变参数模板解压缩typename的参数

cpp*_*hon 8 c++ templates variadic-templates c++11

我想解压缩参数包func(参见第A行),但它不起作用.如何在func <>内解包或仅修改A行?

#include <iostream>
using namespace std;

void func()
{
   cerr << "EMPTY" << endl;
}

template <class A, class ...B> void func()
{
   cerr << "A: "  << endl;
   func<B... >(); // line A
}


int main(void)
{
   func<int,int>();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

预期输出:

A:
A:
Run Code Online (Sandbox Code Playgroud)

编辑:所有答案都非常好.非常感谢

Cas*_*sey 12

有时一次解压缩所有内容更容易,而不是递归.如果你只想要一个参数包for_each,你可以使用braced -init-list扩展技巧的变种(Coliru的现场演示):

template <class A>
void process_one_type() {
    cerr << typeid(A).name() << ' ';
}

template <class ...B> void func()
{
    int _[] = {0, (process_one_type<B>(), 0)...};
    (void)_;
    cerr << '\n';
}
Run Code Online (Sandbox Code Playgroud)

  • 如何理解这个说法?(空白)_; 。这对我来说太花哨了 (2认同)
  • @cppython它将变量`_`转换为类型`void`,这是一个不生成代码的语句表达式,通常只会告诉编译器不要警告`_`未被使用.这是必要的,因为数组`_`仅用于其初始化的副作用. (2认同)

hps*_*use 10

通过使用func<B... >();你暗示这func是一个功能模板,但你之前定义func()的不是.

您需要定义一个func()接受模板参数的模板.这是一个工作示例(在g ++ 4.8.1上):

#include <iostream>
using namespace std;

void func()
{
   cerr << "EMPTY" << endl;
}

template <class ... B>
typename std::enable_if<sizeof...(B) == 0>::type func()
{
}

template <class A, class ...B> void func()
{
   cerr << "A: "  << endl;
   func<B... >(); // line A
}


int main(void)
{
   func();           // This outputs EMPTY
   func<int,int>();  // This will not output EMPTY
   return 0;
}
Run Code Online (Sandbox Code Playgroud)


han*_*aad 8

试试这个:

template <class A> void func()
{
    cerr << "A: " << endl;
}

template <class A, class B, class ...C> void func()
{
    cerr << "A: " << endl;
    func<B, C...>(); // line A
}
Run Code Online (Sandbox Code Playgroud)