Run time type information of base and derived classes
I'm trying to extend the functionality of some classes that I do not have access to.
Basically I'm trying to create a toString/toXML method for logging purposes. I though开发者_StackOverflow中文版t of creating a singleton (essentially a map) to which I can register the different functions and have them globally available in a fashion, so I can have something like string Singleton::toString(void* or abstractObject*)
which would pick the correct method from the map depending on the type.
While I can get type information with typeid, I want to be able to implement it for a base class and then have all derived classes use that method, unless I there is a 'closer' / more appropriate method.
Would that be possible, or should I change to a different method (can templates do that)? I can not access the classes in question unfortunately, as most of them are from 3rd party libraries.
I have found that the following is a very simple way for me to keep track of the types of base and derived structures or classes that I define.
_kind does not have to be a string. In fact, it should probably be an enum. However, since I was designing a rather high level program when I came up with this, strings were fast enough for me.
struct base
{
protected:
string _kind;
public:
base()
{
_kind = "base";
}
~base()
{
}
string kind()
{
return _kind;
}
}
struct derived : base
{
derived()
{
_kind = "derived";
}
~derived()
{
}
}
For built-in structures, perhaps overload the toString and toXML methods and let the compiler decide?
string toString(structure1 A)
{
...
}
string toString(structure2 A)
{
...
}
This might get a little confusing for derived structures, however I think the compiler will choose the leaf structure as the type instead of the base.
For example, if you have types A : B : C : D, and function f is defined for C and A. If you input a variable of type B, then it should be auto typecasted to A. If you input a variable of type C, then it will use the function for type C. If you input a variable of type D, then it should be auto typecasted to type C and then the C function should be called.
You might also try templates which essentially does the same thing.
template <class t>
string toString(t A)
{
...
}
Cheers, Ned
精彩评论