Skip to content

Instantly share code, notes, and snippets.

@s3rvac
Last active December 7, 2023 05:47
Show Gist options
  • Save s3rvac/d1f30364ce1f732d75ef0c89a1c8c1ef to your computer and use it in GitHub Desktop.
Save s3rvac/d1f30364ce1f732d75ef0c89a1c8c1ef to your computer and use it in GitHub Desktop.
Visiting std::variant using lambda expressions in C++17
// $ 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
Copy link

auto visit_variant(auto&& variant, auto&&... alternatives)
{
    return std::visit(overloaded{std::forward<decltype(alternatives)>(alternatives)...},
           std::forward<decltype(variant)>(variant));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment