Home  >  Article  >  Backend Development  >  How Can CRTP Be Used to Achieve Static Polymorphism in C ?

How Can CRTP Be Used to Achieve Static Polymorphism in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 20:33:30124browse

  How Can CRTP Be Used to Achieve Static Polymorphism in C  ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn