In the world of templates you probably want to just specialize templates for each of your types instead of doing a runtime check, ie
template<typename T>
void foo(T obj);
template<>
void foo<MyClassA>(MyClassA obj) {
}
template<>
void foo<MyClassB>(MyClassB obj2) {
}
This will allow the compiler to generate the correct template at compile time by deducing on your args.
Note this only resolves based on a instance's static type, that is there's no compile-time knowledge that your variable is a MyClassC
which inherits from MyClassB
and therefore should use the generic form. So this won't work:
MyClassC* cinstance = new MyClassC();
foo(cinstance); //compiler error, no specialization for MyClassC
In general this points to a general rule that compile-time and run-time polymorphism are very different systems. Templates deal strictly in the realm of static types without knowledge of inheritance. This may surprise folks coming from Java/C# which have a more seamless integration between the two features.
For run-time specialization of functionality for a class, your options are
- Define virtual methods -- may not be appropriate depending if this bit of functionality truly should be a part of this object
- Use dynamic_cast (what you're currently doing) -- somewhat frowned upon, but can be the most straight-forward solution that everyone gets.
- Visitor Pattern -- a design pattern that uses overloading to resolve to a function of the correct type at run-time.
MyClassA
or a pointer to a superclass ofMyClassB
and do the dynamic check. Just trying to interpret though, the goal is kind of ambiguous.