gpt4 book ai didi

c++ - 从可变参数模板类中提取类型以实现成员函数重载

转载 作者:行者123 更新时间:2023-12-02 10:10:47 25 4
gpt4 key购买 nike

我想为可变参数模板类的每种类型提供函数重载。那可能吗 ?

template<typename ...args>
class Example {
virtual void doSomething(args(0) arg) { ... }
virtual void doSomething(args(1) arg) { ... }
/// etc... implementations are the same, but I need access to the type
}
我尝试使用折叠表达式,但是我很确定自己的路线不正确。因为我需要虚函数,所以我不能将它们声明为 template<typename T> virtual void doSomething(T arg),因为不允许模板虚函数。

最佳答案

您可以从基类模板的实例化的模板化包中派生该类,该基类模板使用单个模板参数作为函数参数类型来定义一个虚拟函数。
然后,派生类将为所有虚拟的模板参数类型保存函数重载。

template<typename arg>
class Base {
virtual void doSomething(arg arg) {}
};

template<typename ...args>
class Example : public Base<args>... {};

关于c++ - 从可变参数模板类中提取类型以实现成员函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63620120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com