简体   繁体   English

需要帮助,将可变参数宏扩展为一系列字符串化名称和值

[英]Need help expanding a variadic macro to a sequence of stringified names and values

I know in C++ I can get the name of a macro parameter using the # directive, like so: 我知道在C ++中,我可以使用#指令获取宏参数的名称,如下所示:

#define FOO(value) #value

What I'm trying to figure out is how to convert a list of parameters into a longer list that includes stringified names as well. 我试图弄清楚的是如何将参数列表转换为包含字符串名称的较长列表。 Given FOO(a, b, a+b) I want to get "a", a, "b", b, "a+b", a+b . 给定FOO(a, b, a+b)我想得到"a", a, "b", b, "a+b", a+b

I can do this by creating N macros for potential sequences of up to N parameters, but is there a way to write this with variadic macros? 我可以通过为最多N个参数的潜在序列创建N个宏来做到这一点,但是有没有办法用可变参数宏来编写此宏呢?

Yes, you can use BOOST_PP_ENUM to iterate over the variadic data and add commas between each expansion: 是的,您可以使用BOOST_PP_ENUM遍历可变参数数据并在每个扩展之间添加逗号:

#define FOO(...)                                \
    BOOST_PP_ENUM(                              \
        BOOST_PP_VARIADIC_SIZE(__VA_ARGS__),    \
        MACRO,                                  \
        BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__) \
    )

#define MACRO(z, n, data) \
    BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(n, data)), BOOST_PP_TUPLE_ELEM(n, data)

FOO(a, b, a+b) //"a", a , "b", b , "a+b", a+b

ENUM takes a count of iterations, a macro, and data to give to the macro. ENUM需要迭代计数,宏和要提供给宏的数据。 We pass a PP tuple containing the variadic data. 我们传递一个包含可变参数数据的PP元组。 The macro then accesses the element with index n . 然后,宏访问索引为n的元素。 You can see this work here . 您可以在这里看到这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM