c++ - CRTP to avoid dynamic polymorphism -
how can use crtp in c++ avoid overhead of virtual member functions?
there 2 ways.
the first 1 specifying interface statically structure of types:
template <class derived> struct base { void foo() { static_cast<derived *>(this)->foo(); }; }; struct my_type : base<my_type> { void foo(); // required compile. }; struct your_type : base<your_type> { void foo(); // required compile. };
the second 1 avoiding use of reference-to-base or pointer-to-base idiom , wiring @ compile-time. using above definition, can have template functions these:
template <class t> // t deduced @ compile-time void bar(base<t> & obj) { obj.foo(); // static dispatch } struct not_derived_from_base { }; // notice, not derived base // ... my_type my_instance; your_type your_instance; not_derived_from_base invalid_instance; bar(my_instance); // call my_instance.foo() bar(your_instance); // call your_instance.foo() bar(invalid_instance); // compile error, cannot deduce correct overload
so combining structure/interface definition , compile-time type deduction in functions allows static dispatch instead of dynamic dispatch. essence of static polymorphism.
Comments
Post a Comment