If I have a discriminated union and want to write a function piecewise, the following code works just fine, but is taking advantage of some fairly tricky (at least to me) stuff involving overload groups:
struct A { };
struct B { };
typedef std::variant<A, B> C;
void f(const A & a) { std::cout << "a" << std::endl; }
void f(const B & b) { std::cout << "b" << std::endl; }
void f(const C & c) { std::visit([](const auto & x){ f(x); }, c); }
Is this a recommended way of doing things? Once it's actually written it seems superior to, say, writing something using holds_alternative
.
I have tried to look up what people suggest online, but most of the examples I've seen that make use of std::visit
involve writing literal pages of incomprehensible boilerplate to create visitor classes.