Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 variadic templates and comma-separated expressions equivalence

In a variadic template the ... operator expands a parameter pack into a series of comma-separated arguments (in the simplest form). My question is: how come that calling some_function() for multiple arguments comma-separated works and calling it with the ... operator doesn't?

I'm talking about this code:

template<typename... Args> inline void expand(Args&&... args) 
{
   some_function(22),some_function(32); // Works
   some_function(args)...; // Doesn't work - ERROR
}

Shouldn't these two lines produce a similar output?

like image 827
Paul Avatar asked Dec 11 '22 15:12

Paul


1 Answers

As said in the other answer, the commas you get by expanding a parameter pack are not the comma oparator, but an argument list. Having an argument list as an expression is obviously an error. Since you don't need the return values of the function, you can try something in the lines of this:

template <class... T>
void ignore(T&&...) {}

template<typename... Args> inline void expand(Args&&... args) 
{
   ignore(some_function(args)...); 
}

if however some_function return void, the pack expansion won't work, since you cannot give void "values" to a function. You could either return a value or chain each call of some_function with a comma operator:

template<typename... Args> inline void expand(Args&&... args) 
{
   ignore( (some_function(args),true)...); 
   //or:
   bool b[] = {(some_function(args),true)...};
}
like image 182
Arne Mertz Avatar answered Dec 31 '22 02:12

Arne Mertz