c++ - 可变参数宏

标签 c++ c++11 macros c-preprocessor variadic-macros

有没有办法写这样的宏:

#define G(x1, x2, ... , xn) f(x1), f(x2), ... , f(xn)

或者我是否需要为每个单独的 n 定义它?

C++0x 答案没问题。

编辑:我问的是如何创建这种形式的宏,而不是通常采用可变数量参数的宏。

目标::因此我可以执行以下操作:

#define MAKE_TUPLE(x1, x2, ... , xn) mytuple<decltype((x1)), decltype((x2)), ... , decltype((xn))>{x1, x2, ... , xn}

所以这个 mytu​​ple 可以在没有移动和复制的情况下创建,也不需要对可以使用聚合构造就地创建的临时对象的不必要引用。

最佳答案

如果你愿意使用稍微笨拙的语法,那么你可以使用 Boost.Preprocessor 的序列:

#include <boost/preprocessor.hpp>

#define G(args) BOOST_PP_SEQ_FOR_EACH_I(G_GENF, x, args)
#define G_GENF(r, data, i, elem) \
    BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(i, 0)) f(elem)

用法:

G((a))
G((b)(c))
G((d)(e)(f))

结果:

f(a)
f(b) , f(c)
f(d) , f(e) , f(f)

如果你确实想要 G(a, b, c) 语法,那么因为宏替换不是递归的,我认为你可能需要一个宏来处理你要处理的每个参数通过。不过,您仍然可以从源代码中别处使用的单个宏委托(delegate)给这些宏。考虑:

// Utility for counting the number of args in the __VA_ARGS__ pack:
#define PP_NARGS(...) PP_NARGS2(__VA_ARGS__, PP_NARGS_COUNT())
#define PP_NARGS2(...) PP_NARGS_IMPL(__VA_ARGS__)
#define PP_NARGS_IMPL(x1, x2, x3, N, ...) N
#define PP_NARGS_COUNT() 3, 2, 1, 0, ERROR

// Macros to delegate to concrete, defined-arity implementations:
#define XF(count, ...) XF_IMPL (count, __VA_ARGS__)
#define XF_IMPL(count, ...) XF_ ## count (__VA_ARGS__)

// Defined-arity implementations:
#define XF_1(x1)         f(x1)
#define XF_2(x1, x2)     f(x1), f(x2)
#define XF_3(x1, x2, x3) f(x1), f(x2), f(x3)

// Delegation macro; this is the only macro you need to call from elsewhere:
#define G(...) XF(PP_NARGS(__VA_ARGS__), __VA_ARGS__)    

用法:

G(a)
G(b, c)
G(d, e, f)

结果:

f(a)
f(b), f(c)
f(d), f(e), f(f)

这当然可以进一步推广,一些预处理器实用程序库可能已经有一些工具可以做到这一点,但这演示了如何做到这一点。 (我不熟悉任何 C99/C++0x 预处理器库,所以我不能推荐一个。)

关于c++ - 可变参数宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287583/

相关文章:

c++ - 预编译头设计问题

c++ - 防止派生析构函数中的 vtable 数据竞争

c++ - g++ 不编译带有断言的 constexpr 函数

c - 使用嵌套结构数组进行结构初始化

c - "#define GOT_HERE() ((void)(__LINE__))"的含义?

c++ - 使用 Opencv 分布良好的特征

c++ - 如何迭代结构体中的 unordered_map ?

c++ - 顺序调用 NPN_PluginThreadAsyncCall

c++ - Xcode5 中的 make_unique 可用性?

c - 如何使用宏连接两个正整数?