"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can C++ Achieve Type Erasure: A Comparison of Techniques?

How Can C++ Achieve Type Erasure: A Comparison of Techniques?

Posted on 2025-02-07
Browse:646

How Can C   Achieve Type Erasure: A Comparison of Techniques?

Type Erasure Techniques in C

Type erasure in C refers to the technique of hiding some or all of the type information regarding a class, similar to Boost.Any. Here are various type erasure approaches:

Virtual Functions

Virtual functions are a classic technique where you abstract the implementation of a class inside an interface-based class hierarchy. This approach is adopted by many Boost libraries, such as Boost.Any and Boost.Shared_ptr, to hide types or deallocation mechanisms.

Function Pointers with Templated Functions

An alternative option involves using function pointers with templated functions, while storing the actual object in a void* pointer. Boost.Function utilizes this technique to conceal the real type of a functor.

Template-based Type Erasure without Virtual Functions or Void* Manipulation

For instance, GMan's approach utilizes templates to hide actual types without resorting to virtual functions or void* manipulation.

Shared_Ptr

shared_ptr is a particularly intriguing technique. It leverages function templates in the shared_ptr constructor to store any data and appropriately call the correct destructor at the end. Despite its simplicity, this approach offers convenience by packaging the traditional void*/function-pointer type erasure concept.

Comparison of Techniques

All type erasure techniques in C employ function pointers and void* pointers, with the primary difference being in the provision of semantic sugar.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3