c++ - 有没有办法避免在很多文件中实例化很多模板?

标签 c++ templates cuda instantiation

我正在编写可以使用仿函数的 cuda 内核,仿函数作为模板的参数传递。例如:

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

这些仿函数是在我包含在每个 cpp 文件中的头文件中定义的,对于每个仿函数,我都必须用所有仿函数实例化所有内核:

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

这是很多代码重复,我们必须记住为每个新的仿函数添加一个新行。 有没有办法一次定义所有这些?

最佳答案

看看extern template declarations.

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

Except for inline functions and class template specializations, explicit instantiation declarations have the effect of suppressing the implicit instantiation of the entity to which they refer.

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

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

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

关于c++ - 有没有办法避免在很多文件中实例化很多模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32341278/

相关文章:

C++ 虚拟方法的部分模板特化

C++模板检查类型验证

python - Pycuda - 如何添加-ccbin clang-3.8

C/CUDA - 修改 CUDA/GL 互操作示例以将图像存储在内存缓冲区中

c++ - 如何使用 boost 异常将信息添加到 std::exception

c++ - 如何从 C++ 中的 void 指针复制数据?

非具体类型的 C++ 模板特化(另一个模板类!)

CUDA 无效设备符号错误

c++ - 无法使用 Visual Studio 2019.7.2 编译虚幻引擎 4.25

c++ - 简单的 C++ 文件流