0
#if的最佳替代方案我正在为当前项目使用CUDA,并需要使用单个实现来维护CPU和GPU内核。我可以用#define
__device__ __host__
标记功能,但是这不允许我在需要使用设备专用功能时拆分代码。所以,我想出了以下解决方案:
template <bool IsOnDevice>
#if IsOnDevice
__device__
#else
__host__
#endif
...the rest of the function header
现在,我想将此代码放在一个#定义封装这一部分,如
//Macro:
#define DEVICE_FUNCTION \
template <bool IsOnDevice> \
#if IsOnDevice \
__device__ \
#else \
__host__ \
#endif
//Example function:
DEVICE_FUNCTION
...the rest of the function header
然而,这并未”因为没有其他预处理可以包含在宏中。我也试过
#DEVICE_FUNCTION_true __device__
#DEVICE_FUNCTION_false __host__
#DEVICE_FUNCTION_RESOLVER(flag) DEVICE_FUNCTION_##flag
#DEVICE_FUNCTION \
template <bool IsOnDevice> \
DEVICE_FUNCTION_RESOLVER(IsOnDevice)
,没有运气,因为即使是IsOnDevice在编译时已知的令牌被解析为DEVICE_FUNCTION_IsOnDevice。有没有什么办法可以用#if在宏中(或者其他任何东西)封装代码?
感谢您的评论!我不知道这是很容易区分主机和设备的功能。 –