在专用模板函数中使用通用模板类

Use generalized template class in specialized template functions

本文关键字:函数 专用      更新时间:2023-10-16

我正在为一些基准代码编写一个包装器,并希望为已经模板化的函数中的每个模板化类类型执行相同的代码。

有基准类:

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);