Overload
In this part we'll take a look at overloading and C++ 17 overload uses.
We'll cover the following...
With this utility you can write all lambdas for all matching types in one place:
Press + to interact
std::variant<int, float, std::string> myVariant;std::visit(overload ([](const int& i) { std::cout << "int: " << i; },[](const std::string& s) { std::cout << "string: " << s; },[](const float& f) { std::cout << "float: " << f; }),myVariant;);
Currently, this helper is not a part of the Standard Library (it might be added into with C++20). Let’s see how you can implement it with the code given below.
Implementation
Press + to interact
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };template<class... Ts> overload(Ts...) -> overload<Ts...>;
The code creates a struct
that ...