Example
// C++23
std::visit(overload{
[](int i){ std::print("i={}\n", i); },
[](std::string s){ std::print("s={:?}\n", s); }
}, value);
// C++26
value.visit(overload{
[](int i){ std::print("i={}\n", i); },
[](std::string s){ std::print("s={:?}\n", s); }
});
Puzzle
- Can you implement
member visit
for variant?
// TODO: variant
int main() {
constexpr variant<int, double, float> value = 42;
static_assert(42 == value.visit(overload{
[](int i) { return i; },
[](auto) { return 0; }
}));
}
Solutions
template <class... Ts>
struct overload : Ts... {
using Ts::operator()...;
};
template <class... Ts>
overload(Ts...) -> overload<Ts...>;
template <class... Ts>
struct variant : std::variant<Ts...> {
using std::variant<Ts...>::variant;
constexpr auto visit(auto f) const { return std::visit(f, *this); }
};