RedditPP Mascot

RedditPP

r/cpp • … • u/tcbrindle

Potential C++ extension for type erasure as a language feature

Traditional runtime polymorphism in C++ is achieved by giving every object of polymorphic type an extra hidden pointer member pointing to a vtable -- a struct of function pointers which is used for virtual dispatch. While simple, this approach has a few downsides: adding even a single virtual function to a class hierarchy means that *all* objects now need to carry a vtable pointer. Perhaps more importantly, it's not possible to implement an interface for a type without modifying that type, with likely ABI implications.

There is another approach however, which is instead to use "fat pointers" which bundle together an ordinary object pointer and the vtable pointer only when dynamic dispatch is actually needed. It's the type erasure approach used by languages like Rust and Swift, and also by various C++ libraries like Louis Dionne's [dyno](https://github.com/ldionne/dyno).

Recently Sean Baxter has been experimenting with adding direct language support for "fat pointer" type erasure into his Circle C++ compiler (see Twitter link below). I'd love to see a proposal paper with something like this.

https://twitter.com/seanbax/status/1590236856545071104

— 0