C ++ nested namespaces with macro

This question is based on

I would like to imitate

namespace foo::bar::baz {

      

with a macro before C ++ 17.

I thought in lines:

#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)

      

Based on the second link, but this gives me:

namespace foo { namespacebar { namespacebaz {

      

How do I add a space between namespace

and and identifiers?

Edit:

If you can make a macro to ns(foo::bar::baz)

expand to namespace foo { namespace bar { namespace baz {

, even better.

+3


source to share


2 answers


You can make it much easier with 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)

      



It expands to

namespace foo { namespace bar { namespace baz {

      

+2


source


This can be done much easier:

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

      



You don't need to handle the first namespace separately, and this avoids writing namespace

to a macro NS

.

Demo

+1


source







All Articles