Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
   }
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading