Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call static method form variadic template type parameter?

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?

like image 511
Elvedin Hamzagic Avatar asked Jul 03 '15 10:07

Elvedin Hamzagic


1 Answers

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
}
like image 194
TartanLlama Avatar answered Sep 21 '22 03:09

TartanLlama