ZigZagZebra
ZigZagZebra

Reputation: 1459

Expand parameter pack for a function template

I have a function template as below. The template argument needs to be explicitly given.

template<typename T>
void Func() {...};

I need to call this function for each type in a parameter pack:

template<typename... Inputs>
struct SetStruct{
  void Set() {
    // Call Func() here
  }
};

Is there an easy way to expand the parameter pack? I tried:

Func<Inputs>()...;

and

Func<Inputs>...();

But none of them works.

I can only use C++11 :(

Upvotes: 2

Views: 859

Answers (1)

max66
max66

Reputation: 66200

Is there an easy way to expand the parameter pack? I tried:

Func<Inputs>()...;

If you can use C++17, using the comma operator and template-folding

((void)Func<Inputs>(), ...);

In C++11/C++14, using again the comma operator but in the context of initialization of an unused C-style array, something as follows

template<typename... Inputs>
struct SetStruct{
  void Set() {
    using unused = int[];

    (void)unused { 0, ((void)Func<Inputs>(), 0)... };
  }
};

Observe that, in both cases, I've added a (void) before the call to Func<>().

In your case it's useless (because your Func<>() just return void) but it's a sort of security belt in case of a function that return an object of a class that redefine the comma operator.

Upvotes: 5

Related Questions