Type Erasure

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, std::qsort is generally applicable but also quite error-prone.

When trying to sort a std::vector<int>, we might mistakenly use a comparator that works for C-strings. The compiler can’t catch this error because the necessary type information is missing. Consequentially, we have undefined behavior.

In C++, we can do better.

Object orientation

Here is a straightforward example, which serves as a starting point for further variation.

Get hands-on with 1200+ tech skills courses.