gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:39:28 25 4
gpt4 key购买 nike

我正在编写可以使用仿函数的 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/

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