Last active
December 7, 2023 05:47
-
-
Save s3rvac/d1f30364ce1f732d75ef0c89a1c8c1ef to your computer and use it in GitHub Desktop.
Visiting std::variant using lambda expressions in C++17
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
// $ g++ -std=c++17 -pedantic -Wall -Wextra visit-variant.cpp -o visit-variant | |
// $ ./visit-variant | |
// Implementation: | |
// | |
// Based on http://en.cppreference.com/w/cpp/utility/variant/visit | |
#include <variant> | |
template<typename... Ts> struct make_overload: Ts... { using Ts::operator()...; }; | |
template<typename... Ts> make_overload(Ts...) -> make_overload<Ts...>; | |
template<typename Variant, typename... Alternatives> | |
decltype(auto) visit_variant(Variant&& variant, Alternatives&&... alternatives) { | |
return std::visit( | |
make_overload{std::forward<Alternatives>(alternatives)...}, | |
std::forward<Variant>(variant) | |
); | |
} | |
// Usage example: | |
#include <iostream> | |
#include <string> | |
int main() { | |
std::variant<int, double, std::string> v{"hello"}; | |
// The following call prints "hello": | |
visit_variant(v, | |
[](int i) { std::cout << i << '\n'; }, | |
[](double d) { std::cout << d << '\n'; }, | |
[](const std::string& s) { std::cout << s << '\n'; } | |
); | |
} |
amiteshsingh-cpi
commented
Dec 7, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment