Skip to content

Instantly share code, notes, and snippets.

@HanatoK
Created March 7, 2022 17:55
Show Gist options
  • Save HanatoK/5ca957abc48fd53ed1fdc4231633436a to your computer and use it in GitHub Desktop.
Save HanatoK/5ca957abc48fd53ed1fdc4231633436a to your computer and use it in GitHub Desktop.
C++ map strongly typed enum to type (C++17)
#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