Cppreference provides example usage of std::visit
to access the active member of std::variant
via lambda functions:
https://en.cppreference.com/w/cpp/utility/variant/visit
An abbreviated version of the example code:
#include <iomanip>
#include <iostream>
#include <string>
#include <variant>
// helper type for the visitor
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
// explicit deduction guide (not needed as of C++20)
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main()
{
std::variant<int, long, double, std::string> v("hello");
std::visit(overloaded {
[](auto arg) { std::cout << arg << ' '; },
[](double arg) { std::cout << std::fixed << arg << ' '; },
[](const std::string& arg) { std::cout << std::quoted(arg) << ' '; },
}, v);
}
The comment states that the explicit deduction guide is not needed as of C++20. With this in mind, how would this example code look with C++20 usage?
Simply omitting the explicit deduction guide from the example will not compile in GCC 10.2.