r/cpp • u/ContDiArco • May 01 '26
External Polymorphism in C++26
While developing our Type Erasure library Any++ for C++23, we had to resort to a preprocessor-based EDSL to eliminate the boilerplate.
By studying the "C++26 Reflection Proposals," I was constantly searching for a way to replace this preprocessor programming.
Implementing Type Erasure requires three components:
-
A "V-Table" for indirecting function calls.
-
A "Facade" for the ergonomic connection between the data and the "V-Table."
-
An "Adapter" to connect the functions of the "V-Table" to the specific type.
It suffices to describe one of these components. The other two can then be generated automatically.
One way to do this with C++26 is to specify in code the default adapter and generate the V-table and facade.
C++26 allows you to generate a class using define_aggregate.
The key is that the class can only contain data members.
However, since a data member can have an operator(), member functions can also be simulated this way.
These data members can be specified so that they don't occupy any memory. This allows you to access the enclosing class in the operator() and use the information it manages (the V-table and the data reference).
Interestingly, this method also enables static dispatch with an elegant interface.
To coincide with the GCC16 release and its excellent reflection implementation, I've sketched out such an API:
;
void
;
;
;
;
;
int
This is, of course, just a rough outline. The real value of a type erasure library lies in providing additional runtime capabilities (downcast, crosscast), lifetime mechanisms (shared, unique, value, etc.), and constant correctness.
Any++ provides all of this. As soon as Clang and MSVC also offer reflection, I will implement the presentated technique there.
For now, I have to thank the wizards who created this technical marvel: "C++ compile-time reflection"!
View all comments
Show parent comment
3
u/ContDiArco May 01 '26
Yes! We will see, how they implement this option...