Suppose that we have classes:
class A
{
public:
static void m() {}
}
class B
{
public:
static void m() {}
}
template<typename... T>
class C
{
public:
void c()
{
T::m(); // Call somehow m() of A and B, if T is a parameter pack of A and B
}
}
How I can expand parameter pack and call static method for each type?
The issue with this is that we can't just expand the parameter pack and call it bare inside the function body, because it's not a valid context.
void c()
{
T::m()...; //invalid context for parameter pack expansion
}
There are a number of tricks to get around this. The one I usually use leverages std::initializer_list
:
void c()
{
(void)std::initializer_list<int> { (T::m(), 0)... }; //valid context
}
Demo
In C++17 we will get fold expressions which will simplify things greatly:
void c()
{
(T::m(), ...); //much nicer
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With