在C 中遇到宏的麻烦

Having trouble with macros in C++

本文关键字:麻烦 遇到      更新时间:2023-10-16

我正在尝试编写C 宏来使用模板和类似的颜色名称来定义一堆子类:

#define DECLARE_SET_ELEMENT(color) class ##color##SetElement : public SetElement { public: ##color##SetElement(std::string name); int getValue() override; };

,我可以像以下方式一样使用它:

DECLARE_SET_ELEMENT(Blue) // -> class BlueSetElement ...
DECLARE_SET_ELEMENT(Red)  // -> class RedSetElement ...
...

但是宏定义似乎无法正常工作。我应该按照我的意图工作?

使用

#define DECLARE_SET_ELEMENT(color) class color##SetElement : public SetElement { public: color##SetElement(std::string name); int getValue() override; };

而是。在这种情况下,领先的##不合适。您不想将class关键字与color结合。