Templates 多模板实例化

Templates 多模板实例化,templates,macros,cuda,Templates,Macros,Cuda,我正在设计一个带有模板类的CUDA-C++库。我的类使用了一些模板函数,它们对main和用户都是不可见的。由于要执行编译的两个步骤,我需要显式地专门化它们,否则在链接时会出现“未解决的外部”错误。由于main.cpp中使用了这些类,所以(我猜…)无法告诉nvcc主程序将使用哪些类型,所以我考虑使用一些宏来专门化它们。下面是代码的简化版本: //CUDA_functions.h // CUDA functions declared here and included in files that w

我正在设计一个带有模板类的CUDA-C++库。我的类使用了一些模板函数,它们对main和用户都是不可见的。由于要执行编译的两个步骤,我需要显式地专门化它们,否则在链接时会出现“未解决的外部”错误。由于main.cpp中使用了这些类,所以(我猜…)无法告诉nvcc主程序将使用哪些类型,所以我考虑使用一些宏来专门化它们。下面是代码的简化版本:

//CUDA_functions.h
// CUDA functions declared here and included in files that will be compiled 
// with g++. Those functions are implemented in .cu files, compiled with nvcc
template <typename T>
void foo1(T x);
template <typename T>
void foo2(T x);
template <typename T>
void foo3(T x);

//fileA.h - included in main.cpp
#include "CUDA_functions.h"
template <typename T>
class A {
    // it uses foo1 & foo2 inside
}

//fileB.h - included in main.cpp
#include "CUDA_functions.h"
template <typename T>
class B {
    // it uses foo1 & foo3 inside
}

//macros.h
#define _USE_CLASS_A(T) template void foo1(T); \
    template void foo2(T); /**/
#define _USE_CLASS_B(T) template void foo1(T); \
    template void foo3(T); /**/

//user_spec.cu - template specializations by user. This is the first file to be
//             - compiled and it doesn't know what classes are going to be used
// say, user wants to use classes A & B: HERE THE ERROR RAISES!
#include "macros.h"
_USE_CLASS_A( int );
_USE_CLASS_B( int );

因为用户不必担心这些函数的存在,我想根据他/她要使用的类专门列出它们。最后但并非最不重要的一点是,我没有发现模板的“条件专门化”。我能做些什么来解决这个问题?谢谢大家,我很乐意回答。再见

是主机代码还是设备代码?我相信CUDA不支持设备代码链接。在主机代码中链接模板函数总是有点可疑,不管是CUDA还是无CUDA

与其让你的双手沾满宏,不如把它们放在
名称空间详细信息
的标题中?
按照惯例,
detail
名称空间表示您不应该作为用户访问的库内部内容。

我不确定我是否完全理解您的意图,但CUDA不支持外部链接,因此您的建议可能无法实现。您需要在.cu文件中实例化任何模板化的CUDA代码,以便它最终进入设备编译轨道。是的,我专门在user_spec.cu中使用nvcc编译模板。所以我写了!它是有效的。唯一的问题是我对同一个函数专门化了两次,而g++不喜欢它!啊,我忘了:这不是外部链接,编译器创建单独的对象文件,作为最后一步链接在一起。比如说,main.o CUDA_functions.o和user_spec.o。好的,我会更清楚。CUDA_functions.h是包含在cpp文件中的头文件。如您所见,函数未实现,因为它们是在CUDA_functions.cu中实现的,此处未显示。依赖性在链接阶段得到解决——实际上,当链接器将OBJ连接在一起时。我可以在函数附近写extern“C”,但现在不再需要了。fileA.h和fileB.h包含在main中。宏.h包含在user_spec.cu中,其目的是明确地专门化模板。我再重复一遍:我唯一的问题是双重专业化!一切正常。
#define _USE_FOO1(T) template void foo1(T) /**/
#define _USE_FOO2(T) template void foo2(T) /**/
#define _USE_FOO3(T) template void foo3(T) /**/