Вопрос

I want to write an x-macro that generates some code. The code depends on several headers and is intended to be generated inside namespaces.

The problem is that the xmacro's includes are being included inside the namespaces of the caller. Is there any way I can fix this?

Example:

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
}
Это было полезно?

Решение

Unfortunately no, because X-macros, while being unique, are still ultimately just included files. This is no different from putting #include <iostream> into your own namespace.

X-macro includes should really not do anything but contain the target macro (which has a definition yet to be determined). If the use of your X-macro has prerequisites, I would do something like this:

xmacro_prelude.hpp:

#ifndef XMACRO_PRELUDE_INCLUDED
#define XMACRO_PRELUDE_INCLUDED

#include "foo.hpp"

#endif

xmacro.hpp (usually suffixed with .def, by the way):

#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"
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top