Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Instantiate Template Variadic Class

I have this code:

#include <iostream>

template<class P>
void processAll() {
    P p = P();
    p.process();
}

class P1 {
public:
    void process() { std::cout << "process1" << std::endl; }
};

int main() {
    processAll<P1>();
    return 0;
}

Is there a way to inject a second class ‘P2’ into my function ‘processAll’, using template variadic ? Something like this :

...

template<class... Ps>
void processAll() {
    // for each class, instantiate the class and execute the process method
}

...

class P2 {
public:
    void process() { std::cout << "process2" << std::endl; }
};

...

int main() {
    processAll<P1, P2>();
    return 0;
}

Can we iterate over each class ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With fold expression (c++17), you might do:

template<class... Ps>
void processAll()
{
    (Ps{}.process(), ...);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading