Search code examples
c++non-type-template-parameter

Is there a way to give a specification about the allowed values of a non-type template parameter?


For example, is there a way of saying "n must be larger than 2" in this code?

template<int n>
class MyClass
{
    ...
}

Solution

  • Use requires from C++20:

    template <int n> requires(n > 2) // The parentheses are often optional, but not with this condition.
    class MyClass
    {
        // ...
    };
    

    Alternatively you can use a static_assert:

    template <int n>
    class MyClass
    {
        static_assert(n > 2, "N must be less or equal to 2."); // The description is optional.
        // ...
    };
    

    The first option doesn't let you specify a custom message, but is "SFINAE-friendly", i.e. it's possible to check the condition from a different template without triggering the error on failure. But it doesn't let you specify a custom message. The first option is usually preferred.

    The first option can be replicated pre-C++20 with std::enable_if_t, see @SamVarshavchik's answer.