I have a base class Object
:
struct Object{
};
and n
(in this case 2) classes that inherit from this
struct Integer : public Object{
int i_;
Integer(int i) : i_{i}{}
}
struct Float : public Object{
float f_;
Float(float f) : f_{f}{}
}
By (ab-)using polymorphism I can now store those two types in a vector:
std::vector<Object*> object_list{new Integer(1), new Float(2.1), new Integer(3), new Float(4.2)};
But now I would like to add all those values together.
I can think of...
1) ...defining functions
Integer* add(Integer* i, Integer* j);
Float* add(Integer* i, Float* f);
Float* add(Float* f, Float* g);
Float* add(Float* f, Integer* i);
But this would require to dynamically cast Object
to all available types - twice, which seems like a catastrophe if I have enough children classes.
2) ... Templates, but that won't work, because the types are not known at compile time.
So what is the most efficient way regarding the following requirements:
*Execution time is more important than memory usage (although it should run on an 8GB system)
*It should support an arbitrary number of child classes, but must at least up to 20
*Is not limited to adding, but an arbitrary function f(Object* a, Object* b)
should be supported
*The design of the classes is not yet fixed. If something works that requires change (or changing the total structure in it self) that is possible
*All possible types are known upfront, external DLLs do not need to be supported
*Does not need to support multiple inheritance
*Does not need to be robust in error handling. Recoverable would be nice but I can live with a SEGFAULT.