Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template argument dependent using/typedef declaration

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;
   }
};
like image 639
michuu Avatar asked Feb 12 '26 03:02

michuu


1 Answers

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.

like image 95
Kyle Avatar answered Feb 13 '26 15:02

Kyle