简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM