C++宏嵌套命名空间

3
这个问题基于以下两篇文章: 我希望能够模拟:
namespace foo::bar::baz {

在C++17发布之前,可以使用宏来实现这个功能。
我的想法是:
#define BOOST_PP_VARIADICS
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/fold_left.hpp>
#include <boost/preprocessor/variadic/to_seq.hpp>

#define OP(s, state, x) BOOST_PP_CAT(state, BOOST_PP_CAT( { namespace, x )) {
#define NS(...) namespace BOOST_PP_SEQ_FOLD_LEFT(OP, BOOST_PP_SEQ_HEAD(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)), BOOST_PP_SEQ_TAIL(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))) 

NS(foo, bar, baz)

基于第二个链接,但这给了我:
namespace foo { namespacebar { namespacebaz {

我该如何在namespace和标识符之间添加空格?

编辑:

如果您可以创建一个宏让ns(foo::bar::baz)扩展为namespace foo { namespace bar { namespace baz {,那就更好了。

2个回答

2

您可以使用BOOST_PP_SEQ_FOR_EACH更简单地完成此操作:

#define BOOST_PP_VARIADICS
#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/preprocessor/seq/for_each.hpp>

#define OP(s, state, x) namespace x {
#define NS(...) BOOST_PP_SEQ_FOR_EACH(OP, , BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))

NS(foo, bar, baz)

这将扩展为

namespace foo { namespace bar { namespace baz {

1
这可以更简单地完成:

#define OP(s, state, x) state namespace x {
#define NS(...) BOOST_PP_SEQ_FOLD_LEFT(OP, , BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))

你不需要单独处理第一个命名空间,这使得你不必在 NS 宏中写入 namespace

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接