如何使用宏将 class 声明转换为字符串?

How to convert a class declaration to a string using macros?

我需要将我的 class 声明转换成一个字符串,我还需要定义 class。在下面的代码中,我给出了一个导致 Identifier Person is undefinedIncomplete type not allowed 的示例。但如果自定义宏可以做到这一点,一些代码将不胜感激。

struct Person;
std::string Person::meta = STRINGIFY(
    struct Person{
        static std::string meta;
        std::string name = "Test";
        int age = 5;
        std::string address = "No:35179 Address";
    };
);
Person person;

你不能那样做;您不能在定义类型之前初始化 Person::meta,也不能将类型定义为初始化表达式的一部分。

但是,您可以将初始化移动到宏中:

#define WITH_META(cls, body) struct cls body; std::string cls::meta = "struct " #cls #body;

WITH_META(Person, {
        static std::string meta;
        std::string name = "Test";
        int age = 5;
        std::string address = "No:35179 Address";
    });

int main()
{
    std::cout << Person::meta << std::endl;
}

输出:

struct Person{static std::string meta; std::string name = "Test"; int age = 5; std::string address = "No:35179 Address";}