iFr*_*cht 5 c++ c-preprocessor variadic-macros c++11
我现在读了很多关于可变参数宏的问题,但似乎并没有人回答最简单的问题:
#define IDENTITY(x) x
#define IDENTITY_FOR_ALL(...) ???
Run Code Online (Sandbox Code Playgroud)
有没有办法IDENTITY_FOR_ALL扩展IDENTITY(X)所有参数?任意数量的参数也可能吗?
对于可变参数宏,没有像可变参数模板那样的包扩展这样的东西。
不过,您可以使用 Boost.Preprocessor(或其方法)。
如果您不希望元素之间有任何逗号,请使用
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
#define ID_OP(_, func, elem) func(elem)
#define APPLY_TO_ALL(func, ...) \
BOOST_PP_SEQ_FOR_EACH( \
ID_OP, func, \
BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__) \
)
// example call:
#define SomeTransformation(x) #x // stringize the argument
APPLY_TO_ALL(SomeTransformation, 1, 2, 3) // expands to "1" "2" "3"
Run Code Online (Sandbox Code Playgroud)
演示。用逗号:
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/transform.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>
#define ID_OP(_, func, elem) func(elem)
#define APPLY_TO_ALL(func, ...) \
BOOST_PP_SEQ_ENUM( \
BOOST_PP_SEQ_TRANSFORM( \
ID_OP, func, \
BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__) \
))
// example call:
APPLY_TO_ALL(SomeTransformation, 1, 2, 3) // expands to "1", "2", "3"
Run Code Online (Sandbox Code Playgroud)
演示。检查预处理器输出g++ -std=c++11 -E -P file。