Last active
September 16, 2020 00:15
-
-
Save outro56/c741ee9497ac5342ea39928ff71d4cd8 to your computer and use it in GitHub Desktop.
Building a variant visitor - https://arne-mertz.de/2018/05/overload-build-a-variant-visitor-on-the-fly/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "overload.hpp" | |
#include <iostream> | |
#include <string> | |
#include <variant> | |
int main() { | |
using namespace cmuoh; | |
std::variant<int, float, std::string> intFloatString { "Hello" }; | |
std::visit(overload { | |
[](const int& i) { std::cout << "int: " << i; }, | |
[](const float& f) { std::cout << "float: " << f; }, | |
[](const std::string& s) { std::cout << "string: " << s; } | |
}, | |
intFloatString | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef CMUOH_OVERLOAD_HPP_ | |
#define CMUOH_OVERLOAD_HPP_ | |
namespace cmuoh { | |
template <class ...Fs> | |
struct overload : Fs... { | |
template <class ...Ts> | |
overload(Ts&& ...ts) : Fs{std::forward<Ts>(ts)}... {} | |
using Fs::operator()...; | |
}; | |
template <class ...Ts> | |
overload(Ts&&...) -> overload<std::remove_reference_t<Ts>...>; | |
} //namespace "cmuoh" | |
#endif //CMUOH_OVERLOAD_HPP_ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment