There are two ways.
The first one is specifying the interface statically for the type structure:
template <class Derived> struct base { void foo() { static_cast<Derived *>(this)->foo(); }; }; struct my_type : base<my_type> { void foo();
Secondly, avoid using a reference to a base or a pointer to a base and post at compile time. Using the definition above, you can have template functions that look like this:
template <class T> // T is deduced at compile-time void bar(base<T> & obj) { obj.foo(); // will do static dispatch } struct not_derived_from_base { }; // notice, not derived from base // ... my_type my_instance; your_type your_instance; not_derived_from_base invalid_instance; bar(my_instance); // will call my_instance.foo() bar(your_instance); // will call your_instance.foo() bar(invalid_instance); // compile error, cannot deduce correct overload
Thus, combining the definition of the structure / interface and the deduction of the type of compilation time in your functions allows you to perform static dispatching instead of dynamic dispatch. This is the essence of static polymorphism.
Dean Michael Nov 04 '08 at 19:02 2008-11-04 19:02
source share