My previous question about this subject was answered and I got some tests working nice. Map functions of a class
My question is now, if there is a way to while declaring the function, be able to register it in a map, like I realized in this question about namespaces and classes: Somehow register my classes in a list
the namespaces and classes was fine to register in a map using the "static" keyword, with that, those static instances would be constructed before the main() be called.
Can I do that somehow with class functions?
because when I use static keyword inside a class declaration, I can't initialize the member as I can outside the class declaration(as with namespaces and classes in the second url above)
I guess I could hardcode all members inside the constructor and register them in a map, but I would like to know if there is a way to do that while I declare the members, to make it easier in the future
Thank you,
Joe
What is your problem here ?
The problem is that, unfortunately, in C++ functions are not considered first class members.
Oh sure there are those pointers to functions that work pretty well, but there is no generic function type or anything like that.
There are however ways to work around this, the simplest I think being the
Command
pattern.In the
Command
pattern a function (operation) is abstracted away in an object. The arguments are stored in the object for later reuse (for exampleundo
orredo
command) and a unified interface exists to perform the operation itself.Less talk, more code:
Simple ?
Now, the sweet thing is that I can simply store my command in a map.
This proposal would still require some work.
auto_ptr
or ashared_ptr
would be better for theclone
method...const
and non-const
Foo argument is not that easy to introduce.However it is safer than using a
void*
to store the pointers to function in you map since you have the advantage of RTTI to check whether or not the type is correct.On the other hand, printing the collection of Commands linked to a particular object is incredibly easy now (if you have one map per object), you can also find ways to emulate the effect of
virtual
methods etc...But I hope you realize that you are in fact trying to implement reflection, and it's not gonna be easy... good luck!