Type Erasure

Learn about the type erasure idiom.

Type erasure based on templates is a pretty sophisticated technique. It allows us to bridge dynamic polymorphism (object orientation) with static polymorphism (templates).

First, what does type erasure mean?

Type erasure enables us to use various concrete types through a single generic interface. There are two types of erasure:

  • The C-ish type erasure is a void pointer (void *).
  • Object orientation is the classic C++ -ish way of type erasure.

Let’s start with a void pointer.

Void pointer

Let’s take a closer look at the declaration of std::qsort.

void qsort(void *ptr, std::size_t count, std::size_t size, cmp);

As you can see, we have used cmp method inside the std::qsort. Let’s take a look at it.

int cmp(const void *a, const void *b);

The comparison function cmp should return a:

  • Negative integer: The first argument is less than the second.
  • Zero: Both arguments are equal.
  • Positive integer: The first argument is greater than the second. Thanks to the void pointer,
...