How can I write a using
(or typedef
) declaration that is dependent on a template argument?
I would like to achieve something like this:
template<typename T>
class Class
{
// T can be an enum or an integral type
if constexpr (std::is_enum<T>::value) {
using Some_type = std::underlying_type_t<T>;
} else {
using Some_type = T;
}
};
CodePudding user response:
This is exactly what std::conditional
is for:
template <class T>
class Class
{
using Some_type = typename std::conditional_t<std::is_enum<T>::value, std::underlying_type<T>, std::type_identity<T>>::type;
};
std::type_identity
is from C 20, which if you don't have is easy to replicate yourself:
template< class T >
struct type_identity {
using type = T;
};
This is required since std::underlying_type<T>::type
does not exist if T
is not an enum and std::conditional
can't prevent that evaluation from occurring.