Skip to content

Instantly share code, notes, and snippets.

@cblp
Last active May 29, 2023 10:21
Show Gist options
  • Save cblp/7667e2874443b2a70c5c6a634f6a30bc to your computer and use it in GitHub Desktop.
Save cblp/7667e2874443b2a70c5c6a634f6a30bc to your computer and use it in GitHub Desktop.
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