Last active
May 29, 2023 10:21
-
-
Save cblp/7667e2874443b2a70c5c6a634f6a30bc to your computer and use it in GitHub Desktop.
ADT in C++. Based on https://dev.to/tmr232/that-overloaded-trick-overloading-lambdas-in-c17
This file contains hidden or 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
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; | |
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; | |
template<class Variant, class... Ts> | |
auto match(Variant v, Ts... matchers) { | |
return visit(overloaded{matchers...}, v); | |
} | |
struct Human {string name; int age;}; | |
struct Animal {string kind; int age;}; | |
using Species = variant<Human, Animal>; | |
int main() { | |
Species species = Human{"John", 100}; | |
// example 1 | |
visit( | |
overloaded{ | |
[](Human const & human) { | |
cout << "Human name: " << human.name << endl; | |
}, | |
[](Animal const & animal) { | |
cout << "Animal kind: " << animal.kind << endl; | |
}, | |
}, | |
species | |
); | |
// example 2 | |
match( | |
species, | |
[](Human const & human) { | |
cout << "Human name: " << human.name << endl; | |
}, | |
[](Animal const & animal) { | |
cout << "Animal kind: " << animal.kind << endl; | |
} | |
); | |
// example 3 | |
cout | |
<< match( | |
species, | |
[](Human human ){return "Human name: " + human .name;}, | |
[](Animal animal){return "Animal kind: " + animal.kind;} | |
) | |
<< endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment