C++实例化模板variadic类
我有此代码:
#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;
}
是否有一种方法可以使用模板variadic将第二类“ P2”注入我的函数'ProcessAll'中?这样的事情:
...
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;
}
我们可以在每个班级上迭代吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用C ++ 17的折叠表达式,您可以将多个进程的执行转发到常见的“单程
p
”实现:如果
processsingle的逻辑()
很简单,则可以跳过如 @jarod42的答案所示,将其实现在单独的函数中,而将所有功能放在折叠表达式中。Using C++17's fold expressions you may forward execution of several processes to the common "process single
P
" implementation: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.使用 fold表达式(c ++ 17),您可能会做:
With fold expression (c++17), you might do: