C++ 实例化可变参数模板类

4

我有这段代码:

#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;
}

有没有一种使用模板可变参数的方法,可以将第二个类'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;
}

我们可以迭代每个类吗?

2个回答

5

使用C++17的折叠表达式,您可以将多个进程的执行转发到通用的“处理单一 P”实现:

template<typename P>
void processSingle() {
    P p = P();
    p.process();
}

template<typename... Ps>
void processAll() {
    (processSingle<Ps>(), ...);
}

如果processSingle()的逻辑简单,您可以跳过在单独函数中实现它,而是将所有内容放入折叠表达式中,如@Jarod42的答案所示。


请您帮忙纠正以下语句:“you skip could implement the it within”。谢谢。 - Aamir

2
使用 C++17 的折叠表达式,你可以这样做:
template<class... Ps>
void processAll()
{
    (Ps{}.process(), ...);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接