Skip to content

Instantly share code, notes, and snippets.

@tuket
Created July 13, 2018 15:54
Show Gist options
  • Save tuket/0e4eb648bfd7a4251922d9fc77c263c5 to your computer and use it in GitHub Desktop.
Save tuket/0e4eb648bfd7a4251922d9fc77c263c5 to your computer and use it in GitHub Desktop.
variant_numbers.cpp
#include <variant>
#include <string>
#include <vector>
#include <exception>
#include <functional>
#include <iostream>
using namespace std;
void numToStringNum(variant<int, string>& x)
{
static vector<string> names = {
"zero", "one", "two", "three", "four", "five", "six", "seven"
};
int ix = get<int>(x);
if(ix < 0 || ix >= (int)names.size()) {
x = "unknown";
}
else {
x = names[ix];
}
}
int main()
{
vector<variant<int, string>> numbers = {0, 1, 2, 4, 8};
for_each(numbers.begin(), numbers.end(), numToStringNum);
for_each(numbers.begin(), numbers.end(), [](auto& a){ visit([](auto& a){cout << a << endl;}, a); });
return 0;
}
@tuket
Copy link
Author

tuket commented Jul 13, 2018

Output:

zero
one
two
four
unknown

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