宏依赖宏 [英] macro dependent macro

查看:145
本文介绍了宏依赖宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能做这样的事情:

  #define F(x)\ 
#ifdef DOUBLE \
2 * x \
#else \
x \
#endif

,这样当我使用 F 时,它的扩展取决于宏 DOUBLE 是否定义?我不这么认为,但我很有希望。 GNU扩展很好。

编辑
为了回应一些答案,我真的使用它来做一些代码代,代码根据定义的位置略有不同。由于包含某些文件的顺序以及需要定义相关宏的位置,因此要切换它需要一些分解。我可能不得不这样做,但如果我不必从这个角落解开我自己就会感到兴奋!

我们可以限制问题,你可以做到这一点。具体而言,如果您可以保证 DOUBLE 或者


  • 未定义为宏,或
  • 被定义为一个扩展为空令牌序列的宏(例如 #define DOUBLE ),



  • 那么你可以使用间接方式和令牌串联:

      #define F_IMPL_(x)DOUBLE_IS_DEFINED 
    #define F_IMPL_DOUBLE(x)DOUBLE_NOT_DEFINED

    #define F_1(x,m)F_2(x,m)
    #define F_2 (x,m)F_IMPL_ ## m(x)

    #define F(x)F_1(x,DOUBLE)

    使用范例:

    pre $ F $
    #define DOUBLE
    F(t)

    预处理结果:

      DOUBLE_NOT_DEFINED 
    DOUBLE_IS_DEFINED

    如果 DOUBLE (如果定义的话)定义为一个扩展为单个已知标记的宏,如果该标记可以形成标识符的一部分(例如, TRUE 1 )。要处理这个问题,你只需将 F_IMPL _ 宏重命名为 F_IMPL_ {TOKEN} (例如 F_IMPL_TRUE F_IMPL_1 )。


    Is it possible to do something like this:

      #define F(x) \
        #ifdef DOUBLE \
          2*x \
        #else \
          x \
        #endif
    

    so that when I use F, what it expands to depends on whether the macro DOUBLE is defined? I don't think so, but I'm hopeful. GNU expansions are fine.

    Edit In response to some of the answers, I'm really using this to do some code generation, where the code is slightly different depending on where it gets defined. Because of the order in which some files are included and where the relevant macros need to be defined, switching it around that way requires a bit of factoring. I may have to do it, but would be thrilled if I don't have to unpaint myself from this corner!

    解决方案

    If we can constrain the problem, you can accomplish this. Specifically, if you can guarantee that DOUBLE is either

    • not defined as a macro, or
    • is defined as a macro that expands to an empty token sequence (e.g. #define DOUBLE),

    then you can use an indirect approach with token concatenation:

    #define F_IMPL_(x)       DOUBLE_IS_DEFINED
    #define F_IMPL_DOUBLE(x) DOUBLE_NOT_DEFINED
    
    #define F_1(x, m) F_2(x, m)
    #define F_2(x, m) F_IMPL_ ## m ( x )
    
    #define F(x) F_1(x, DOUBLE)
    

    Usage example:

    F(t)
    #define DOUBLE
    F(t)
    

    Result after preprocessing:

    DOUBLE_NOT_DEFINED
    DOUBLE_IS_DEFINED
    

    This approach will also work if DOUBLE (if it is defined) is defined as a macro that expands to a single known token, if that token can form part of an identifier (e.g., TRUE or 1). To handle this, you just have to rename the F_IMPL_ macro to F_IMPL_{TOKEN} (e.g., F_IMPL_TRUE or F_IMPL_1).

    这篇关于宏依赖宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆