Simulating Rust Trait in C++

I got in touch with rust quite early and watched its ecosystem gradually improve. When I first used trait, I wondered how to implement such a great feature in c++. Though it wasn’t an urgent need, I put it aside. Recently, I tried to implement it in a simple way. Rust Trait Let’s first look at an example of rust trait. Simply put, it’s about defining interfaces, implementing interfaces, and interface polymorphism. Actually, c++ already has a complete inheritance paradigm to implement these requirements - virtual interface, inheritance implementation, virtual polymorphism. However, virtual functions require forced dynamic dispatch and add virtual table pointers to class instances. So let’s try to implement trait without using virtual inheritance. ...

March 12, 2025 · 4 min · hypengw