Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ nested namespaces with a macro

This questions is based on

  • C++ namespaces advice and
  • C++ preprocessor--join arguments

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.

like image 568
PSkocik Avatar asked Dec 05 '25 10:12

PSkocik


1 Answers

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 {
like image 129
vitaut Avatar answered Dec 07 '25 00:12

vitaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!