How is type erasure implemented in C++?
We have seen what type erasure looks like in C++. Now we understand what it means for a program to not explicitly depend on a type. But the mystery remains—the program makes no mention of the type, and yet, at the right time, invokes an operation on the type it knows nothing about. How? That is what we are about to see.
Very old type erasure
The idea of writing a program without explicit type information is certainly not new. In fact, it predates object-oriented programming and the notion of objects by a long time. Consider this C program (no C++ here) as an example:
// Example 06 int less(const void* a, const int* b) { return *(const int*)a - *(const int*)b; } int main() { int a[10] = { 1, 10, 2, 9, 3, 8, 4, 7, 5, 0 }; qsort(a, 10, sizeof(int), less); }
Now remember the function declaration for qsort
from the standard C
library:
void qsort(void *base, size_t nmemb, size_t size, ...