在实现CUDA代码期间,我经常需要一些实用程序函数,这些函数将从设备和主机代码中调用.所以我将这些函数声明为__host__ __device__.这是可以的,#ifdef CUDA_ARCH可以处理可能的设备/主机不兼容性.
当效用函数被模板化时出现问题,即.通过一些仿函数类型.如果模板实例调用__host__函数,我会收到此警告:
calling a __host__ function from a __host__ __device__ function is not allowed
detected during instantiation of "int foo(const T &) [with T=HostObject]"
Run Code Online (Sandbox Code Playgroud)
我知道的唯一解决方案是定义函数两次 - 一次用于设备,一次用于具有不同名称的主机代码(我不能重载__host__ __device__).但这意味着存在代码重复和所有其他__host__ __device__将调用它的函数,也必须定义两次(甚至更多的代码重复).
简化示例:
#include <cuda.h>
#include <iostream>
struct HostObject {
__host__
int value() const { return 42; }
};
struct DeviceObject {
__device__
int value() const { return 3; }
};
template <typename T>
__host__ __device__
int foo(const T …Run Code Online (Sandbox Code Playgroud) cuda ×1