本文介绍了#if inside #define?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些旧代码,通过#defines生成大量代码。现在我知道在 #define 内不可能有 #ifdef ,但是 #if 可能?我想为一个特定类型添加一些专门化。 (不进行重大更改,如使用模板)。以下示例给出了我们的隐藏错误,因此这不是这样的:

I'm sitting on some legacy code that generates a lot of code through #defines. Now I know it's not possible to have an #ifdef inside a #define, but is an #if possible? I would like to do add some specialization for a specific type. (without making major changes like using templates instead). The following sample gives me cryptic errors so this is not the way:

#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);


推荐答案



You could achieve that with templates:

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)

这篇关于#if inside #define?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 17:36