在专用模板函数中使用通用模板类
Use generalized template class in specialized template functions
我正在为一些基准代码编写一个包装器,并希望为已经模板化的函数中的每个模板化类类型执行相同的代码。
有基准类:
template<class T>
class Benchmark : public Interface, public T {
virtual void Execute();
}
作为类 T,我想使用一个基本上仅用于初始化类变量的类型,例如
template<class S>
struct GenericBench {
GenericBench();
S var1, var2, var3;
};
现在的问题是:对于这种类继承结构,是否有可能以某种方式为GenericBench的每个突变定义一个专门的函数Execute?
template<>
void Benchmark<GenericBench>::Execute() {
// my benchmark code
}
然后,主调用将如下所示:
myBench->Execute<GenericBench<int>>();
以下代码在 g++ 中编译和链接
struct Interface { };
template<class T>
class Benchmark: public Interface, public T {
public:
virtual ~Benchmark() { }
virtual void Execute();
};
template<class S>
struct GenericBench {
GenericBench() { }
S var1, var2, var3;
};
// Specialization of the class
template<class S>
class Benchmark<GenericBench<S> >: public Interface, public GenericBench<S> {
public:
virtual ~Benchmark() { }
virtual void Execute() {
// do things
}
};
int main(int argc, char **argv) {
Benchmark<GenericBench<int> > myBench;
myBench.Execute();
}
既然你说你想根据你正在处理的类型定义专门的响应......制作函数模板,然后专门化它会有所帮助。
下面是一个示例(很抱歉没有使用您提供的示例。我只是想展示方法。让我知道它是否适合您)
template <class S> class myData {
public:
};
namespace mySpecializedFunction {
template<class P> void someFunction(P check) {std::cout<<"3333n";return;}
template<> void someFunction(myData<int> check) {std::cout<<"4444n";return;}
template<> void someFunction(myData<float> check) {std::cout<<"5555n";return;}
}
template <class T> class myClass: public T {
public:
template <class Q> void someFunction( Q check) { mySpecializedFunction::someFunction(check); return ; }
};
并像这样使用它...
myData<int> d1;
myData<float> d2;
myClass< myData<int> > c1;
c1.someFunction(d1);
myClass< myData<float> > c2;
c2.someFunction(d2);
相关文章:
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 使用 C++20 概念模板函数专用化时的依赖项
- 将 c++ 类成员函数专用于模板类
- 使用模板模板参数进行模板定义的函数专用化
- 返回值的简单模板类成员函数专用化
- 已专用类的成员函数专用化
- 部分模板函数专用化enable_if:默认实现
- 使用数组参数进行函数专用化
- 模板函数专用化的内部编译器错误
- 在子类中定义可变参数函数专用化
- 使用模板的构造函数专用化
- 模板函数专用化Enable_if
- 如何将模板构造函数专用化移动到 cpp 文件
- 模板类模板构造函数专用化
- 模板类是否可以用作模板函数专用化的参数
- 未调用数组的函数专用化
- 如何将模板成员函数专用化为另一个模板类
- 模板类的模板函数专用化
- 参数值的自动模板函数专用化
- 如何在类中使用成员函数专用化