Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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();
}
like image 617
jcoder Avatar asked Oct 27 '25 16:10

jcoder


1 Answers

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(), ...);
like image 126
Quentin Avatar answered Oct 30 '25 07:10

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!