【问题标题】:macro expansion to additional macro arguments对附加宏参数的宏扩展
【发布时间】:2016-12-14 13:22:37
【问题描述】:

我正在寻找一种制作扩展为额外参数的宏的方法:

int constant1=2, constant2=3;
#define add_three_arguments(x,y,z) x+y+z
#define extra_arguments ,constant1,constant2
#define make_value(A) add_three_arguments(A extra_arguments)

int r = make_value(5);

【问题讨论】:

  • 为什么你想要一个宏,而你肯定可以使用一个函数来做到这一点?
  • 不直接相关,位从不定义像#define add_three_arguments(x,y,z) x+y+z这样的宏,但总是将表达式放入(),如下所示:#define add_three_arguments(x,y,z) (x+y+z)。否则,如果您使用x = add_three_arguments(1,2,3) * 10,结果将不是您所期望的。
  • 如果您能告诉我们您在这里尝试实现的更高级别的目标,那将非常有帮助。
  • 这对我来说就像XY Problem

标签: c macros arguments


【解决方案1】:

我找到的最接近的解决方案是:

int constant1=2, constant2=3;
#define _add_three_arguments(x,y,z) x+y+z
#define add_three_arguments(...) _add_three_arguments(__VA_ARGS__)

#define extra_arguments ,constant1,constant2
#define make_value(A) add_three_arguments(A extra_arguments)

int r = make_value(5);

这当然不是我所说的问题的解决方案。所以目前的答案似乎是,“这是不可能的”。但也许新版本的 clang/gcc 会以某种方式实现这一点。我将保留这个问题。

【讨论】:

    【解决方案2】:

    尝试以下方法:

    #define EMPTY
    #define EVAL(X) X
    #define add_three_arguments(x,y,z) x+y+z
    #define extra_arguments ,constant1,constant2
    #define make_value(A) EVAL(add_three_arguments EMPTY (A extra_arguments))
    
    make_value(5);
    

    但是,如果您重新设计宏,您可能会得到一个更好的解决方案,而不需要此类结构。

    【讨论】:

      猜你喜欢
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2016-05-14
      相关资源
      最近更新 更多