#if inside #define?

混江龙づ霸主 提交于 2019-12-10 13:37:08

问题


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

回答1:


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)



回答2:


Why you dont write it like this:

#if (type == double)
    #define MK_GET  some code
#else
    #define MK_GET  same code with changes
#endif



回答3:


#if cannot be nested inside #define. Why you want to avoid templates when that is the better choice. They are safe and "compilable" (not preprocessed).




回答4:


The pre-processor is one pass process, so you can't place macro defines inside of macro defines. The only way to do this is via the template interface.



来源:https://stackoverflow.com/questions/8427963/if-inside-define

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!