C++实例化模板variadic类

发布于 2025-02-07 20:58:44 字数 707 浏览 1 评论 0原文

我有此代码:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江挽川 2025-02-14 20:58:44

使用C ++ 17的折叠表达式,您可以将多个进程的执行转发到常见的“单程p”实现:

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

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

如果processsingle的逻辑()很简单,则可以跳过如 @jarod42的答案所示,将其实现在单独的函数中,而将所有功能放在折叠表达式中。

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.

俏︾媚 2025-02-14 20:58:44

使用 fold表达式(c ++ 17),您可能会做:

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

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

template<class... Ps>
void processAll()
{
    (Ps{}.process(), ...);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文