Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variadic template unpacking arguments to typename

I want to unpack the parameter pack in func (see line A), but it doesnt work. How can I unpack inside func< > or modify Line A only?

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

An expected output :

A:
A:

edited: all of answers are very good. thanks alot

like image 556
cppython Avatar asked Jan 17 '14 07:01

cppython


People also ask

How to unpack parameter pack c++?

To unpack a parameter pack, use a templated function taking one (or more) parameters explicitly, and the 'rest' of the parameters as a template parameter pack.

What is the use of Variadic templates?

With the variadic templates feature, you can define class or function templates that have any number (including zero) of parameters. To achieve this goal, this feature introduces a kind of parameter called parameter pack to represent a list of zero or more parameters for templates.

What is Variadic template in C++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration.

What is parameter pack in C++?

Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.


1 Answers

Sometimes it's easier to unpack everything at once, instead of recursively. If you simply want a parameter pack for_each, you can use a variant of the braced-init-list expansion trick (Live demo at 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';
}
like image 84
Casey Avatar answered Sep 21 '22 11:09

Casey