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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that is clean. I expected a lot more wizardry to be necessary - thanks! Accepting as soon as the system will let me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.