Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum-only templated class

Is there any way to ensure that a templated class will fail to compile if a specific template argument is supplied with something other than a strongly-typed enumeration (i.e. enum class)?

like image 303
Conduit Avatar asked Apr 10 '26 23:04

Conduit


1 Answers

Use a trait and static_assert.

I.e.

template <class T>
using is_scoped_enum = std::integral_constant<bool, !std::is_convertible<T, int>{}
                                                  && std::is_enum<T>{}>;

template <typename T>
struct myTemplate
{
   static_assert( is_scoped_enum<T>{}, "Invalid type argument!" );
};

(Taken from this answer.)
Demo.

like image 79
Columbo Avatar answered Apr 13 '26 11:04

Columbo