【问题标题】:Macro resulting from evaluation of other macros not evaluated由评估其他未评估的宏产生的宏
【发布时间】:2016-08-15 13:07:22
【问题描述】:

我对 C 预处理器的工作方式有疑问。我已经写了下面的代码。当使用OPREP(n) 时,它应该会产生如下结果: OP(0,OP(1,OP(2,OP(3, .... OP(n,。然后我想要实现的是当我添加 whatever)))))))n 右括号之类的东西时,我应该得到 OP(0,OP(1,OP(2,OP(3, .... OP(n,whatever))))))) 应该评估为 0 1 2 3 4 5 .... n whatever.

#include <boost/preprocessor/comma.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/punctuation/paren.hpp>

#define OP(a,b) a b
#define T0() OP
#define OPMAC(z,n,s) T0()BOOST_PP_LPAREN() n BOOST_PP_COMMA()
#define OPREP(n_) BOOST_PP_REPEAT(n_, OPMAC, a)

OPREP(2) 3))

当我编译并查看预处理器输出时,我得到: OP( 0 , OP( 1 , 3))。那就是它没有评估生成的 OP() 宏。 我的问题是为什么,以及如何强制对其进行评估?

【问题讨论】:

  • 对我来说听起来有点像 XY 问题;实际想要输出什么?为什么要手动输入表达式的右半部分并生成左半部分?
  • @m.s.这是一个最小的例子。在实践中,宏 OP 接受 3 个参数 - 运行计数器、text1 和 text2。每个嵌套的 OP 调用的 text1 和 text2 都发生了很大的变化(因此我希望能够编辑它们,它不仅仅是本示例中的单个参数 whatever,而是 n 不同的嵌套 whatevers)。虽然正确的部分没有改变 - 它只是带有运行计数器的 OP。如果 n=20 写 OP(0,OP(1,OP(2 20 次) 可能会很烦人。我意识到可以有其他实现。我可以想到几个。但我想知道为什么这个没有工作。

标签: boost macros c-preprocessor boost-preprocessor


【解决方案1】:

我想通了。要强制进行另一次评估,我需要做的就是添加一个虚拟的 FORCE_EVAL 宏,该宏的评估结果与其参数相同,并将我的调用包含在其中:

#include <boost/preprocessor/comma.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/punctuation/paren.hpp>

#define OP(a,b) a b
#define T0() OP
#define OPMAC(z,n,s) T0()BOOST_PP_LPAREN() n BOOST_PP_COMMA()
#define OPREP(n_) BOOST_PP_REPEAT(n_, OPMAC, a)
#define FORCE_EVAL(...) __VA_ARGS__

FORCE_EVAL(OPREP(2) 3)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    相关资源
    最近更新 更多