When I tried to iterate over variadic arguments via the following function
I don't understand '{(Print(Param),0)... } 'where 0 is used
#include<iostream>
using namespace std;
template<typename T>
void Print(T& arg)
{
cout << arg << endl;
}
template<typename ...ParamTypes>
void Func(ParamTypes &...Param)
{
int arr[] = { (Print(Param),0)... };
}
int main()
{
int num = 10;
Func(num,num,num);
return 0;
}
It gives me an error when I don't add 0
As
Print
if a (template) function returningvoid
, some hack is needed to manipulate it in an expression. Here:the comma operator (
,
) is used to make sure the side-effect ofPrint
is manifested and yet something is returned: the zeroint
. Indeed, you cannot construct an array ofvoid
s.As a reminder, the comma operator evaluates its left-hand operand, discards its result, and finally returns its right-hand operand.
It is in my humble opinion a bad hack. A more clear/explicit could be constructed:
demo on godbold