简体   繁体   中英

Can I call a function on ALL base classes in a parameter pack expansion?

Is there a way to have my run function below call the run functions of all the bases classes contained in the parameter pack? Either using standard c++ facilities/libraries or my own template metaprogramming? C++11 preferred but interested in later standards too.

Code simplified to the most basic example. I originally had a use case for this, but now I'm mostly just interested in if it can be done to improve my understanding.

template <class ...Bases> class Test : public Bases...
{
public:
    void run()
    {
        // QUESTION: I want to call the run function of ALL the bases, 
        //           Is there a way to do this that compiles and works?
        Bases.run()...;
    }
};

class One
{
public:
    void run() {}
};

class Two
{
public:
    void run() {}
};

int main()
{
    Test<One, Two> test;
    test.run();
}

Well, it's just usual pack-expansion. The fact that they are your base classes doesn't interfer much.

C++11:

int _[]{0, (void(Bases::run()), 0)...};
(void) _;

C++17:

(void)(Bases::run(), ...);

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