3

This questions is based on

I would like to emulate

namespace foo::bar::baz {

with a macro before C++17 arrives.

I was thinking in the lines of:

#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 the identifiers?

Edit:

If you can make a macro so that ns(foo::bar::baz) expands to namespace foo { namespace bar { namespace baz {, even better.

Community
  • 1
  • 1
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142

2 Answers2

2

You can do it much simpler 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)

This expands to

namespace foo { namespace bar { namespace baz {
vitaut
  • 49,672
  • 25
  • 199
  • 336
1

This can be done much simpler:

#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 have to treat the first namespace separately, and this allows you not to write namespace in the NS macro itself.

Demo

Anton Savin
  • 40,838
  • 8
  • 54
  • 90