Home > Back-end >  How to Stringify a class declaration and define it?
How to Stringify a class declaration and define it?

Time:09-22

I need to convert my class declaration into a string and I also need the class defined. in the code below i have given an example which results in Identifier Person is undefined or Incomplete type not allowed. but is if this is possible with custom macros, some code would be much appreciated.

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;

CodePudding user response:

You can't do that; you can't initialize Person::meta before the type is defined, and you can't define the type as part of the initializing expression.

However, you can move the initialization into the macro:

#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;
}

Output:

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