#define 中 #if 的最佳替代方法是什么

What is the best alternative to #if in #define

我正在为我当前的项目使用 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)

运气不好,因为令牌被解析为 DEVICE_FUNCTION_IsOnDevice,即使 IsOnDevice 在编译时已知。有没有什么方法可以用#if 将代码封装在宏(或任何其他东西)中?

您可以使用 __CUDA_ARCH__ 预定义宏来区分代码是否应被视为设备代码。在主机端,宏未定义。

这是一个例子:

__device__ __host__ void foo()
{
#ifdef __CUDA_ARCH__
    __syncthreads();
#else
    // do something else on host side
#endif
}