Created
March 7, 2022 17:55
-
-
Save HanatoK/5ca957abc48fd53ed1fdc4231633436a to your computer and use it in GitHub Desktop.
C++ map strongly typed enum to type (C++17)
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 <vector> | |
#include <utility> | |
#include <type_traits> | |
enum class Foo { | |
A1, A2 | |
}; | |
enum class Bar { | |
B1, B2 | |
}; | |
template <Foo> struct foo_enum_to_type; | |
template <Bar> struct bar_enum_to_type; | |
template <> struct foo_enum_to_type<Foo::A1> {using type = int;}; | |
template <> struct foo_enum_to_type<Foo::A2> {using type = double;}; | |
template <> struct bar_enum_to_type<Bar::B1> {using type = std::string;}; | |
template <> struct bar_enum_to_type<Bar::B2> {using type = std::vector<int>;}; | |
template <auto EnumVal> | |
constexpr auto enum_to_type_impl() { | |
if constexpr (std::is_same_v<decltype(EnumVal), Foo>) { | |
return foo_enum_to_type<EnumVal>{}; | |
} else { | |
return bar_enum_to_type<EnumVal>{}; | |
} | |
} | |
template <auto EnumVal> | |
struct enum_to_type { | |
using type = typename decltype(enum_to_type_impl<EnumVal>())::type; | |
}; | |
int main() { | |
enum_to_type<Bar::B2>::type x; | |
x.resize(10); | |
enum_to_type<Bar::B1>::type s{"Hello"}; | |
std::cout << "Size of x: " << x.size() << std::endl; | |
std::cout << s << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment