Somehow register my classes in a list

后端 未结 2 1155
北荒
北荒 2020-11-28 13:27

I would like to be able to register my classes within a std::map or a vector, don\'t think about duplicates and such for now, but I don\'t want to register it

相关标签:
2条回答
  • 2020-11-28 13:36

    Use boost::mpl, vector or map.

    0 讨论(0)
  • 2020-11-28 13:47

    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; }
    
    0 讨论(0)
提交回复
热议问题