【问题标题】:#include inside an x-macro#include 在 x 宏中
【发布时间】:2012-10-18 20:57:23
【问题描述】:

我想编写一个生成一些代码的 x 宏。该代码依赖于几个标头,旨在在命名空间内生成。

问题是 xmacro 的包含被包含在调用者的命名空间中。有什么办法可以解决这个问题吗?

例子:

xmacro.hpp:

#include "foo.hpp"
struct bar {
BODY
};
#undef BODY

main.hpp:

namespace ns {
  #define BODY int func();
  #include "xmacro.hpp" // inserting foo.hpp inside namespace ns
}

【问题讨论】:

    标签: c++ c-preprocessor x-macros


    【解决方案1】:

    很遗憾,没有,因为 X 宏虽然是独一无二的,但最终仍然只是包含文件。这与将#include <iostream> 放入您自己的命名空间没有什么不同。

    X-macro 包含实际上不应该做任何事情,而是包含目标宏(其定义尚未确定)。如果使用您的 X-macro 有先决条件,我会这样做:

    xmacro_prelude.hpp:

    #ifndef XMACRO_PRELUDE_INCLUDED
    #define XMACRO_PRELUDE_INCLUDED
    
    #include "foo.hpp"
    
    #endif
    

    xmacro.hpp(顺便说一下,通常以 .def 为后缀):

    #ifndef XMACRO_PRELUDE_INCLUDED
        #error "You must include xmacro_prelude.hpp prior to using this X-macro."
    #endif
    
    struct bar {
    BODY
    };
    
    #undef BODY
    

    main.hpp:

    #include "xmacro_prelude.hpp"
    
    namespace ns {
      #define BODY int func();
      #include "xmacro.hpp"
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-17
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      相关资源
      最近更新 更多