Static Polymorphism via CRTP
To eliminate the performance overhead associated with virtual member functions, C offers the CRTP (Curiously Recurring Template Pattern). This technique facilitates the creation of a statically defined interface for a hierarchy of types, enabling compile-time dispatch.
Alternative Implementations
CRTP can be leveraged in two distinct ways:
1. Static Interface Specification:
<code class="cpp">template <class Derived> struct base { void foo() { static_cast<Derived *>(this)->foo(); }; };</code>
2. Compile-Time Wiring:
<code class="cpp">template <class T> void bar(base<T> &obj) { obj.foo(); // static dispatch }</code>
Example Usage:
Using these approaches, you can create a statically dispatched interface with compile-time type deduction:
<code class="cpp">struct not_derived_from_base { }; my_type my_instance; not_derived_from_base invalid_instance; bar(my_instance); // calls my_instance.foo() bar(invalid_instance); // compile error (incorrect overload deduction)</code>
The above is the detailed content of How Can CRTP Be Used to Achieve Static Polymorphism in C ?. For more information, please follow other related articles on the PHP Chinese website!