Home > Backend Development > C++ > body text

How Does Curiously Recurring Template Pattern (CRTP) Achieve Static Polymorphism in C ?

Mary-Kate Olsen
Release: 2024-10-27 05:48:02
Original
752 people have browsed it

How Does Curiously Recurring Template Pattern (CRTP) Achieve Static Polymorphism in C  ?

Avoiding Runtime Polymorphism with CRTP

In C , the use of virtual member functions introduces additional overhead at runtime. CRTP (Curiously Recurring Template Pattern) presents an alternative approach to avoiding this overhead while preserving polymorphism.

There are two methods for employing CRTP to achieve this goal.

Static Type Specialization

The first method involves defining the interface statically for the structure of types. This is achieved by creating a base template class with a virtual member function. Derived classes can then instantiate this template class and implement the virtual member function:

<code class="cpp">template <class Derived>
struct Base {
  virtual void foo() {}
};

struct MyType : Base<MyType> {
  void foo() override;
};

struct YourType : Base<YourType> {
  void foo() override;
};</code>
Copy after login

Static Dispatch via Compile-Time Type Deduction

The second method eschews the use of reference-to-base or pointer-to-base idioms. Instead, wiring is established at compile-time through template functions that deduce the type at runtime:

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

Using this method, only derived classes from Base can be passed to bar. This allows for static dispatch and eliminates the overhead associated with virtual member functions:

<code class="cpp">bar(MyType()); // Calls MyType::foo()
bar(YourType()); // Calls YourType::foo()</code>
Copy after login

In conclusion, CRTP offers a powerful mechanism for achieving static polymorphism in C . By either specializing the interface for the type structure or performing static dispatch via compile-time type deduction, developers can avoid the runtime overhead of virtual member functions while maintaining the flexibility of polymorphism.

The above is the detailed content of How Does Curiously Recurring Template Pattern (CRTP) 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!