how to call member functions when the objects is variable template parameters? Here's a example:
template <typename ...A>
void f(A... args)
{
args->memfunc("examples")...; // the code not right!
}
How to do it right?
how to call member functions when the objects is variable template parameters? Here's a example:
template <typename ...A>
void f(A... args)
{
args->memfunc("examples")...; // the code not right!
}
How to do it right?
That's rather tricky. A parameter pack can be expanded only in certain contexts. You can't just write a statement expanding it (without C++17 fold expressions). The usual trick involves using a dummy array initializer (which is a possible context with well defined evaluation order):
int dummy[] = { // Expand it in the initializer
(void(args->memfunc("examples")), 0)...
};
We don't want to force a specific return type on all the members. So we use the comma operator (..., 0)
to create an expression that always has an int
type. However, since operators can be overloaded we need to cast the result of the function call to void in order to make sure we use the built-in one. So the expression we expand ends up being what you see.
In C++17, you can use a fold expression:
template <typename ...A>
void f(A... args)
{
(..., args->memfunc("examples")); // the code not right!
}