Is there a way avoid having to instantiate a lot of templates in a lot of files?

时间:2015-09-01 21:35:51

标签: c++ templates cuda instantiation

I'm writing cuda kernels that can make use of functors, that are passed as a parameter with templates. For example:

template<typename Functor> void myKernel(float arg1, float* arg2, Functor f) {
  // Do stuff that will involve f
}

These functors are defined in a header file that I include in each cpp file, and for each one I have to instantiate all the kernels with all the functors:

template<> myKernel<Add>(float, float*, Add)
template<> myKernel<Sub>(float, float*, Sub)

This is a lot of code duplication, and we have to remember to add a new line for each new functor. Is there a way to define all of this once?

2 个答案:

答案 0 :(得分:1)

查看extern template declarations.

有一些关于extern模板的细微细节,尤其是14.7.2.10:

  

除内联函数和类模板特化外,   显式实例化声明具有抑制的效果   他们引用的实体的隐式实例化。

这意味着以下内容仅会抑制其他翻译单元中非内联成员函数f的实例化,但不能用于g:

template<typename T> class A {
public:
     void g() {} // inline member function
     void f();
};

template<typename T> void A::f() {} // non-inline

答案 1 :(得分:0)

Just add the instanciations in the header file, and you won't have to remember to specify them every time.