if class is foo, use a new implementation else use an old implementationThere are many ways to achieve this. The naive way is as shown below.
1 2 3 4 5 | if (instance.type() == "foo" ) { instance.new_impl(); } else { instance.old_impl(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class foobar_base { public : virtual ~foobar_base() {} virtual void impl() = 0; } class foo : public foobar_base { public : virtual ~foo() {} void impl() { cout << "New implementation" << endl; } }; class bar : public foobar_base { public : virtual ~bar() {} void impl() { cout << "Old implementation" << endl; } } void do_something( const foobar_base& fb) { fb.impl(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include <iostream> using namespace std; template < typename T> struct impl_traits { static const bool value = false ; }; template < typename T> void do_something() { if (impl_traits<T>::value) { T::new_impl(); } else { T::old_impl(); } }; class foo { public : static void old_impl() { cout << "[foo] Old implementation" << endl; } static void new_impl() { cout << "[foo] New implementation" << endl; } }; class bar { public : static void old_impl() { cout << "[bar] Old implementation" << endl; } static void new_impl() { cout << "[bar] New implementation" << endl; } }; template <> struct impl_traits<foo> { static const bool value = true ; }; int main() { do_something<foo>(); do_something<bar>(); return 0; } |
[foo] New implementation [bar] Old implementation