我现在在 SO 上阅读了很多关于可变参数宏的问题,但似乎没有人回答过最简单的问题:
#define IDENTITY(x) x
#define IDENTITY_FOR_ALL(...) ???
有没有办法让所有参数的 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"
Demo . 带逗号:
#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"
Demo .
使用 g++ -std=c++11 -E -P file
检查预处理器输出。
关于c++ - 是否可以对每个参数进行可变参数宏替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26474896/