The primary choice for including on-time in C ++ is a virtual function.
This is dead simple:
#include <string> #include <iostream> using namespace std; struct Base { virtual void g() const = 0; }; template< class Type > void g( Type const& ); template<> void g( int const& ) { cout << "int" << endl; } template<> void g( string const& ) { cout << "string" << endl; } template<> void g( char const& ) { cout << "char" << endl; } template< class Type > struct Derived: Base { Type t; virtual void g() const override { ::g<Type>( t ); } }; void f( Base& b ) { bg(); } int main() { Derived<int>().g(); }
As you can, this is also effective, O (1) instead of stupid O ( n ). Also, with checking the type of static (compilation time) instead of checking the type of dynamic time (runtime), saving a rather annoying amount of testing. What more can I say? Indeed, forget about type code and enums and the like. Remember that Bertrand Meyer decided not to support Eiffel enumerations, which is why people tend to abuse them for type codes. Use virtual functions.
Hi virtual features!
They are really useful if you need dynamic type submission otherwise.
So, I recommend using virtual functions for this. :)
EDIT : templatized ::g to avoid possible ambiguities in real code.
source share