views:

213

answers:

2

Hi,

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 instanciate 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...

Thanks,
Joe

+5  A: 

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; }
Alexandru
Sorry, but I didn't understand it... how would I do to declare the class with your code?
Jonathan
except for std::string / string
ScottJ
@Jonathan: posted the example about XYZ. Is this what you wanted?
Alexandru
I think he wants to be able to do `class REGISTERED_CLASS(MyClass) { /* ... */ };`
Georg Fritzsche
@Alexandru: Yes, thanks!
Jonathan
@gf: I can do that with what he wrote, couldn't I?
Jonathan
A: 

Use boost::mpl, vector or map.

rama-jka toti