Last active
November 26, 2022 10:53
-
-
Save daig/6500d3246ef40b514b52e17ba108a027 to your computer and use it in GitHub Desktop.
Variant cases with concepts
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
#include <iostream> | |
#include <vector> | |
#include <variant> | |
#include <string> | |
using namespace std; | |
template<typename ... Ts> | |
struct cases : Ts ... {using Ts::operator() ...; }; | |
template<class... Ts> cases(Ts...) -> cases<Ts...>; | |
template<typename T> | |
concept printable = requires(T a) { | |
{ cout << a } -> same_as<ostream&>; | |
}; | |
struct complex { double re, im; }; | |
ostream& operator<<(ostream& os, complex c) { | |
return os << c.re << " + " << c.im << "i"; | |
} | |
int main(){ | |
using types = variant<string, long, int, long long, complex>; | |
vector<types> vecVariant = {"hello", '2', 100ll, 2011l, 2017, complex{2, 1}}; | |
for (auto v : vecVariant) { | |
visit( cases { | |
[](string) { cout << "string" << endl; }, | |
[](int) { cout << "int" << endl; }, | |
[](unsigned int) { cout << "unsigned int" << endl; }, | |
[](long int) { cout << "long int" << endl; }, | |
[](long long int) { cout << "long long int" << endl; }, | |
[](printable auto i) { cout << "unknown type (" << i << ")" << endl; } | |
}, v); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment