In the world of templates, you probably want to just specialize templates for each of your types instead of checking the runtime, i.e.
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, outputting your arguments.
Note this is only allowed based on the static type of the instance , that is, there is no compilation time knowledge that your variable is MyClassC , which inherits from MyClassB and therefore must use a common form, so this will not work:
MyClassC* cinstance = new MyClassC(); foo(cinstance); //compiler error, no specialization for MyClassC
In general, this indicates a general rule that polymorphisms of compilation time and runtime are very different systems. Templates deal exclusively with static types without knowledge of inheritance. This may surprise people from Java / C # who have a smoother integration between the two functions.
To specialize the functionality for the class at runtime, your parameters
- Defining virtual methods may not be appropriate if this bit of functionality really needs to be part of this object.
- Using dynamic_cast (what you are doing now) is a bit of a frown, but it might be the most direct solution that everyone gets.
- A visitor pattern is a design pattern that uses overload to resolve a function of the correct type at run time.
source share