[英]C++ template specialization for enum
我想將已知類型映射到我自己定義的枚舉值。
enum class MyType : uint8_t {
Int8,
Uint8,
Int16,
Uint16,
Int32,
Uint32,
... // some other primitive types.
};
template <typename T>
constexpr uint8_t DeclTypeTrait();
template <>
constexpr uint8_t DeclTypeTrait<int8_t>() {
return static_cast<uint8_t>(MyType::Int8);
}
... // Specialize for each known number type.
同樣對於用戶定義的任何枚舉類型,我想將其映射到 Int32。 用戶必須在 int32_t 上定義他的枚舉類。
using Enumeration = int32_t;
// Some user defined enum.
enum class CameraKind : Enumeration {
Perspective,
Orthographic
};
所以我像這樣實現 DeclTypeTrait :
template <typename T,
class = typename std::enable_if<std::is_enum<T>::value>::type>
constexpr uint8_t DeclTypeTrait() {
return static_cast<uint8_t>(MyType::Int32);
}
但我收到錯誤:“調用 'DeclTypeTrait' 不明確”
candidate function [with T = CameraKind]
candidate function [with T = CameraKind, $1 = void]
我的問題是如何做到這一點:
// If a have a variable of known types or any enum on int32.
int8_t v1;
CameraKind camera;
std::string s;
DeclTypeTrait<decltype(v1)>() -> MyType::Int8
DeclTypeTrait<decltype(camera)>() -> MyType::Int32
DeclTypeTrait<decltype(s)>() // Report compile error is OK.
對於您的情況,使用類模板會簡單得多。
template <typename T, typename = std::void_t<>>
struct DeclTypeTraitT {
};
template <typename T>
inline constexpr uint8_t DeclTypeTrait = DeclTypeTraitT<T>::value;
template <>
struct DeclTypeTraitT<int8_t> {
static constexpr uint8_t value = static_cast<uint8_t>(MyType::Int8);
};
template <typename T>
struct DeclTypeTraitT<T, std::enable_if_t<std::is_enum_v<T>>> {
static constexpr uint8_t value = static_cast<uint8_t>(MyType::Int32);
};
然后
CameraKind camera;
static_assert(DeclTypeTrait<decltype(camera)> == static_cast<uint8_t>(MyType::Int32));
正如@HolyBlackCat 所說,如果你想映射底層類型,你可以使用
template <typename T>
struct DeclTypeTraitT<T, std::enable_if_t<std::is_enum_v<T>>> {
static constexpr uint8_t value = DeclTypeTrait<std::underlying_type_t<T>>;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.