Somehow register my classes in a list

Here is method to put classes names inside a vector. Leave a comment if I missed important details. I don’t think it will work for templates, though.

struct MyClasses {
    static vector<string> myclasses;
    MyClasses(string name) { myclasses.push_back(name); }
};

#define REGISTER_CLASS(cls) static MyClasses myclass_##cls(#cls);

struct XYZ {
};

REGISTER_CLASS(XYZ);

The trick here is to make some computation before main() is called and you can achieve this via global initialization. REGISTER_CLASS(cls) actually generates code to call the constructor of MyClasses at program startup.

UPDATE: Following gf suggestion you can write this:

#define REGISTER_CLASS(cls) temp_##cls; static MyClasses myclass_##cls(#cls); class cls
class REGISTER_CLASS(XYZ) { int x, y, z; }

Leave a Comment