问题
I would like to know if it was possible to merge several macros in C++
Let me explain : I have an A macro that does not do anything at all. I want to add a macro B to A so that A = A + B, then I want to add a macro C to A so that A becomes A = A + C, and so that A contains B and C. I also want these operations to be done in different .h files and not in a single file like that :
// in Component.h
#define A
class Component
{
}
class myXmlParser
{
template <class T>
void addComponent<T>()
{
myComponents.push_back(new T);
}
std::vector<Component> myComponents;
}
// in PlayerScript.h
#include "Component.h"
class Player : public Component
{
#define A \
myParser.addComponent<Player>();
}
// in Enemy.h
#include "Component.h"
class Enemy : public Component
{
#define A \
myParser.addComponent<Enemy>();
}
// in main.cpp
void main()
{
myXmlParser myParser;
A
}
and the output is :
void main()
{
myXmlParser myParser;
myParser.addComponent<Player>();
myParser.addComponent<Enemy>();
}
Now, if the user need to add another script, he dont need to touch the main, only his script.
Thank you ! Please !
回答1:
It is not possible to #define
one macro with the value of a macro (the same or another). (It is of course possible to use one macro in another’s definition, but it is expanded only when the (outermost) macro is expanded.) It is therefore impossible to “accumulate” anything into a macro.
What you want to do is typically accomplished by defining non-local variables whose initializations accumulate some data structure to use (from some sort of iteration) later. As always, be aware of the subtleties of their initialization order; if you can use them, C++17 and C++20 add features to control that (inline
and modules, respectively).
来源:https://stackoverflow.com/questions/59110026/merge-macros-c