7

我坐在一些通过#defines 生成大量代码的遗留代码上。现在我知道不可能有一个#ifdef内部 a #define,但有#if可能吗?我想为特定类型添加一些专业化。(无需进行重大更改,例如使用模板)。以下示例给了我神秘的错误,所以这不是方法:

#define MK_GET(type) \
  type get_ ## type (int index) \
  { \
    #if type == double \  <-- what i want to add
      specialized code... \
    #endif
    ...
  } \

MK_GET(double);
MK_GET(int);
MK_GET(string);
4

4 回答 4

7

您可以使用模板来实现:

template<typename T>
struct getter
{
    T operator()(int index)
    {
        // general code
    }
};

template<>
struct getter<double>
{
    T operator()(int index)
    {
        // specialized code
    }
};

#define CAT(a, b) a ## b
#define MK_GET(type) type CAT(get_, type) (int index) getter<type>()(index)
于 2011-12-08T08:18:56.287 回答
1

预处理器是一次通过过程,因此您不能将宏定义放在宏定义中。唯一的方法是通过模板界面。

于 2011-12-08T08:20:56.417 回答
0

为什么你不这样写:

#if (type == double)
    #define MK_GET  some code
#else
    #define MK_GET  same code with changes
#endif
于 2011-12-08T08:16:55.667 回答
0

#if不能嵌套在里面#define。为什么你想避免templates 当那是更好的选择。它们是安全且“可编译的”(未预处理)。

于 2011-12-08T08:17:22.997 回答