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

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

Patricia Arquette
Release: 2024-10-28 20:33:30
Original
229 people have browsed it

  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>
Copy after login

2. Compile-Time Wiring:

<code class="cpp">template <class T>
void bar(base<T> &obj) {
  obj.foo(); // static dispatch
}</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template