upvote
To add to sibling comment...

GCC 11 (2021) std::visit was slower than virtual dispatch.

GCC 12 (2022) optimized std::visit so it can be faster than virtual dispatch.

https://shubhankar-gambhir.github.io/posts/your-stdlib-imple...

reply
If you take the linked benchmark and use the latest compiler version, the std::variant version is faster. The annoying thing about std::variant (and with some other features of modern C++) is that it generates a bunch of code that the compiler has to optimize away.
reply
Somehow and for some reason rust enums don’t have this problem and are far more ergonomic and easier to work with (not to mention compile times are amazing). I don’t know exactly why it’s better to have it as a first class language primitive and why the compiler has such a problem with std::visit, but clearly c++ meta programming slows down things in a super linear way such that the compiler has problems both from code gen and then optimization.
reply