Somehow register my classes in a list

2019-01-07 20:29发布

问题:

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 within the class constructor call or any within function of the class, somehow do it outside the class so even if I never instantiate it, I would be able to know that it exists.

Example:

// Somehow, from outside the myclass, in a scope that will be called
//in the begining of the proccess, add "MyClass1" to a 
//list so it can be instanciated later
class MyClass1{

}

Then I would make a #define of it or if able, a template.
I don't know if I made myself clear(again)... My point is that I need to know every class that I have without having to call every and each of them.
My idea was to create a #define to make it easier to declare the header of the class and call something that would register that specific class to a list

Can this be done or will I have to map it manually?

// desirable:
#define CLASSREGISTER(myclass) makethemagic(##myclass); class myclass {
};

I know, with that define I couldn't use inheritance etc... My point was to try to give an example of what I was thinking to create somehow...

回答1:

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


回答2:

Use boost::mpl, vector or map.