【问题标题】:C++ nested namespaces with a macro带有宏的 C++ 嵌套命名空间
【发布时间】:2015-09-15 00:02:01
【问题描述】:

这个问题是基于

我想效仿

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 {,那就更好了。

【问题讨论】:

    标签: c++ macros c-preprocessor


    【解决方案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

    Demo

    【讨论】:

      【解决方案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 {
      

      【讨论】:

        猜你喜欢
        • 2013-09-11
        • 2011-03-13
        • 1970-01-01
        • 2013-01-14
        • 1970-01-01
        • 2011-01-06
        • 1970-01-01
        • 1970-01-01
        • 2019-08-03
        相关资源
        最近更新 更多