Šimon Tóth’s Post

View profile for Šimon Tóth

C++ Educational Content Creator | 20 years of Software Engineering experience distilled into digestible daily posts

When working with std::variant, processing the current active member can lead to cumbersome code. An alternative, especially when the processing code is generic, is the std::visit. The std::visit requires as an argument an invocable that is compatible with each of the contained types. This can be achieved through a combination of concrete and generic operator() overloads. Compiler Explorer link: https://lnkd.in/edud3tc4 #cpp #cplusplus #coding #programming #dailybiteofcpp

  • text

What about performance of using std::visit?Seems that standard implementation is not so optimized

Like
Reply

The only safe way to deal with a `std::variant` is `std::visit`. I'm not fond of overload idiom tough. Pattern matching can be achieved via `if constexpr`, at expense of some syntax noise. Using `get` or `get_if` can go wrong for a typo, and you're doomed at runtime.

Too bad we have to write that weird `overloaded` struct ourselves. Is there a reason why it's not in the standard?

See more comments

To view or add a comment, sign in

Explore content categories