BOOST_PP在空序列情况下扩展序列 [英] BOOST_PP expand sequence in the empty sequence case

查看:61
本文介绍了BOOST_PP在空序列情况下扩展序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 BOOST_PP ,我可以使用一个附加令牌将宏扩展为多个逗号分隔的值,如下面的代码所示.

Using BOOST_PP I can expand a macro into multiple comma separated values with an additional token, as can be seen in the below code.

但是,在无参数的情况下它不起作用.

However, it doesn't work in the no-argument case.

#define BOOST_PP_VARIADICS
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>

#define ADD_TOKEN(r, token, i, e) \
    BOOST_PP_COMMA_IF(i) token(e)

#define WRAP(...) \
    BOOST_PP_SEQ_FOR_EACH_I(ADD_TOKEN, decltype, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))

#define MACRO(fmt, ...) \
    Template<WRAP(__VA_ARGS__)>

MACRO("");
MACRO("", 0);
MACRO("", 0, 1);

使用 gcc -E main.cpp 进行编译时的输出为

The output when compiling with gcc -E main.cpp is

Template< decltype() >;
Template< decltype(0) >;
Template< decltype(0) , decltype(1) >;

如何在没有 __ VA_ARGS __ 参数扩展为null的情况下获得对 MACRO 的调用?

How can I get calls to MACRO with no __VA_ARGS__ arguments expand to null?

也就是说,我希望输出为:

That is, I'd like the output to be:

Template< >;
Template< decltype(0) >;
Template< decltype(0) , decltype(1) >;

我该如何实现?

推荐答案

此答案使用GNU扩展名.您在评论中表示可以接受.

This answer uses a GNU extension. You stated in the comments that you're okay with that.

您可以使用 BOOST_PP_TUPLE_SIZE((,## __VA_ARGS __)):当且仅当省略可变参数时,它会为您提供 1 .

You can use BOOST_PP_TUPLE_SIZE((, ## __VA_ARGS__)): it will give you 1 if and only if the variadic arguments are omitted.

模板有点棘手,因为它们可以包含不带括号的逗号,当在宏参数中使用时会引起混淆.以这种方式编写代码需要花费一些工作,使得 WRAP 宏仅在 BOOST_PP_IF 已经完成后才展开:

Templates are a bit tricky in that they can contain unparenthesised commas, which cause confusion when used in macro arguments. It takes a bit of work to write it in such a way that the WRAP macro is only expanded after BOOST_PP_IF has finished already:

#define MACRO(fmt, ...) \
    Template< \
    BOOST_PP_IF(BOOST_PP_EQUAL(BOOST_PP_TUPLE_SIZE((,##__VA_ARGS__)), 1), \
        BOOST_PP_EXPAND, WRAP) (__VA_ARGS__) \
    >

注意:我在空的情况下使用 BOOST_PP_EXPAND ,因为 BOOST_PP_EXPAND(__ VA_ARGS __)将扩展为空.

Note: I'm using BOOST_PP_EXPAND in the empty case, because BOOST_PP_EXPAND(__VA_ARGS__) will expand to nothing.

这篇关于BOOST_PP在空序列情况下扩展序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆