[英]Map enum values to corresponding types with templates at compile time?
我有一個想法,在編譯時使用模板將枚舉值映射到相應的數據類型。 我怎樣才能做到這一點?
例如
enum DataType {
UNSINGED_INT; // uint32_t
INT; // int32_t
UNSIGNED_CHAR; // uint8_t
CHAR; // int8_t
}
auto type = MapToDataType<DataType::UNSIGNED_CHAR>; // type will be uint8_t in this case
如果您的enum
包含可轉換為int
的值序列,沒有孔,並且從零開始(如您的示例中所示),您可以使用std::tuple
作為類型映射和std::tuple_element
來提取所需的類型。
所以,寫一個輔助結構如下
template <DataType dt>
struct MapToDataType_helper
{
using type = typename std::tuple_element<
static_cast<std::size_t>(dt),
std::tuple<std::uint32_t,
std::int32_t,
std::uint8_t,
std::int8_t>
>::type;
};
您的地圖是一個簡單的模板,使用
template <DataType dt>
using MapToDataType = typename MapToDataType_helper<dt>::type;
例如,您可以驗證
static_assert( std::is_same_v<MapToDataType<DataType::UNSIGNED_CHAR>,
std::uint8_t> );
template <DataType> struct MapToDataTypeHelper {};
template <> struct MapToDataTypeHelper<INT> {using type = int;};
template <> struct MapToDataTypeHelper<UNSIGNED_INT> {using type = unsigned int;};
// ...
template <DataType X> using MapToDataType = typename MapToDataTypeHelper<X>::type;
MapToDataType<INT> x; // int x;
首先你專門化一個類模板,然后你使用別名模板:
#include <cstdint>
enum class DataType {
UNSIGNED_CHAR,
UNSIGNED_INT,
CHAR,
INT
};
template <DataType> struct MapToDataType;
template <> struct MapToDataType_t<DataType::UNSIGNED_CHAR> { using type = std::uint8_t; };
template <> struct MapToDataType_t<DataType::UNSIGNED_INT> { using type = std::unit32_t; };
template <> struct MapToDataType_t<DataType::CHAR> { using type = std::int8_t; };
template <> struct MapToDataType_t<DataType::INT> { using type = std::nit32_t; };
template <DataType T>
using MapToDataType = typename MapToDataType_t<T>::type;
一些標記類型和值來攜帶編譯時值和類型:
template<auto x>
using constant_t = std::integral_constant<std::decay_t<decltype(x)>, x>;
template<auto x>
constexpr constant_t<x> constant{};
template<class T>
struct tag_t{using type=T;};
template<class T>
constexpr tag_t<T> tag{};
template<class X>
constexpr void type_map( X ) {}
template<auto X>
using get_type = typename decltype(type_map(constant<X>))::type;
好了,機器完成了。
現在只需添加這些:
inline auto type_map( constant_t<DataType::UNSIGNED_INT> ) { return tag<std::uint32_t>; }
inline auto type_map( constant_t<DataType::INT> ) { return tag<std::int32_t>; }
inline auto type_map( constant_t<DataType::UNSIGNED_CHAR> ) { return tag<std::uint8_t>; }
inline auto type_map( constant_t<DataType::CHAR> ) { return tag<std::int8_t>; }
它有效。
支持其他枚舉只是將type_map
重載添加到相關enum
的命名空間中。
一個宏
#define TYPE_MAP(FROM,...) \
inline auto type_map( constant_t<FROM> ) { return tag<__VA_ARGS__>; }
可以讓它不那么冗長。
get_type
現在可以在任何設置了相同機制的枚舉上統一工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.