3

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)?

Conduit
  • 2,675
  • 1
  • 26
  • 39

1 Answers1

7

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.

Community
  • 1
  • 1
Columbo
  • 60,038
  • 8
  • 155
  • 203
  • Wow, that is clean. I expected a lot more wizardry to be necessary - thanks! Accepting as soon as the system will let me. – Conduit Nov 23 '14 at 01:15