Created
April 8, 2024 05:56
-
-
Save jupiterbjy/29d6e3b2e8619c04e2e2faf2259d6f4a to your computer and use it in GitHub Desktop.
Some test code to see behavior of `std::variant` and `std::visit`
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 <iostream> | |
#include <string> | |
#include <variant> | |
template<class... Types> | |
struct overloaded : Types... { using Types::operator()...; }; | |
template<class... Types> | |
overloaded(Types...)->overloaded<Types...>; | |
using VARIANT = std::variant<int, wchar_t*, char*, std::wstring, std::string, bool, std::nullptr_t>; | |
struct SomeClass { | |
void _func(const int arg) { | |
std::cout << "int overload called" << std::endl; | |
} | |
void _func(const std::string& arg) { | |
std::cout << "string overload called" << std::endl; | |
} | |
void _func(const std::wstring& arg) { | |
std::cout << "wstring overload called" << std::endl; | |
} | |
void _func(const char* arg) { | |
std::cout << "char* overload called" << std::endl; | |
} | |
void _func(const wchar_t* arg) { | |
std::cout << "wchar_t* overload called" << std::endl; | |
} | |
void _func(bool arg) { | |
std::cout << "Boolean overload called" << std::endl; | |
} | |
void _func (std::nullptr_t arg) { | |
std::cout << "nullptr_t overload called" << std::endl; | |
} | |
void func(const VARIANT& arg) { | |
std::cout << "Variant called" << std::endl; | |
std::visit(overloaded{ | |
[&](const int arg) { _func(arg); }, | |
[&](const char* arg) { _func(arg); }, | |
[&](const wchar_t* arg) { _func(arg); }, | |
[&](const std::string& arg) { _func(arg); }, | |
[&](const std::wstring& arg) { _func(arg); }, | |
[&](const bool arg) { _func(arg); }, | |
[&](const std::nullptr_t& arg) { _func(arg); } | |
}, arg); | |
} | |
}; | |
int main() { | |
std::string temp = "mew"; | |
SomeClass a; | |
a.func(1); | |
a.func("ABCD"); | |
a.func(temp); | |
a.func(L"ABCD"); | |
a.func(true); | |
a.func(nullptr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live
Output: