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 ?
CodePudding user response:
Using C 17's fold expressions you may forward execution of several processes to the common "process single P
" implementation:
template<typename P>
void processSingle() {
P p = P();
p.process();
}
template<typename... Ps>
void processAll() {
(processSingle<Ps>(), ...);
}
If the logic of processSingle()
is simple you could skip implementing it in a separate function and instead place all of it within the fold expression, as shown in @Jarod42's answer.
CodePudding user response:
With fold expression (c 17), you might do:
template<class... Ps>
void processAll()
{
(Ps{}.process(), ...);
}