Created
February 8, 2019 23:38
-
-
Save gmbeard/25631362f74576e0837a5be1f39a4a87 to your computer and use it in GitHub Desktop.
Variant return type
This file contains 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 <variant> | |
#include <iostream> | |
#include <string> | |
struct A { }; | |
struct B { }; | |
struct C { }; | |
using Object = std::variant<A, B, C>; | |
Object factory(int i) { | |
switch (i) { | |
case 0: | |
return A { }; | |
case 1: | |
return B { }; | |
default: | |
return C { }; | |
} | |
} | |
void use_object(A) { | |
std::cout << "A\n"; | |
} | |
void use_object(B) { | |
std::cout << "B\n"; | |
} | |
void use_object(C) { | |
std::cout << "C\n"; | |
} | |
bool parse_number(char const* arg, int& num) { | |
char const* begin = arg; | |
char const* end = begin + std::strlen(arg); | |
num = 0; | |
for (; begin != end; ++begin) { | |
int n = *begin - '0'; | |
if (n > 9 || n < 0) { | |
return false; | |
} | |
num = (num * 10) + n; | |
} | |
return true; | |
} | |
int main(int argc, char const** argv) { | |
int n; | |
if (argc < 2 || !parse_number(argv[1], n)) { | |
std::cerr << "Please provide a positive number!\n"; | |
exit(1); | |
} | |
std::visit( | |
[](auto&& obj) { use_object(std::move(obj)); }, | |
factory(n) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment