【发布时间】:2016-06-30 16:30:28
【问题描述】:
我在当前项目中使用 CUDA,并且需要通过单一实现来维护 CPU 和 GPU 内核。我可以用
标记一个函数__device__ __host__
但这不允许我在需要使用仅限设备的功能时拆分代码。所以,我想出了以下解决方案:
template <bool IsOnDevice>
#if IsOnDevice
__device__
#else
__host__
#endif
...the rest of the function header
现在,我想把这段代码放在一个#define中来封装这部分,比如
//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 的代码封装在宏中(或其他任何东西)?
【问题讨论】:
标签: c cuda macros c-preprocessor maintainability