假设我有以下两种类型:
enum class TypeA {
//...
};
class TypeB {
public:
using _type = unsigned int;
constexpr _type to_type();
//...
};
我想设计一个SFINAE模板方法,这样,如果类型T是普通枚举(即不具有_type(,则选择版本1,如果类型确实具有typedef_type
,则选择版本2。
版本1(如果T是正常枚举(:
template<typename T>
inline constexpr std::underlying_type_t<T> underlying_cast(T p) { return static_cast<std::underlying_type_t<T>>(p); }
版本2:
template<typename T>
inline constexpr typename T::_type underlying_cast(T p) { return p.to_type(); }
我该怎么做?我也非常感谢解释SFINAE模板在这种情况下是如何工作的。
您不一定需要SFINAE:
template<typename T>
constexpr auto underlying_cast(T p) {
if constexpr (std::is_enum_v<T>) return static_cast<std::underlying_type_t<T>>(p);
else return p.to_type();
}
https://godbolt.org/z/o17ebbMxo