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

Time:10-03

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

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

CodePudding user response:

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.

CodePudding user response:

The classical approach is to use an additional, defaulted, template parameter:

#include <type_traits>

template<int n, typename=std::enable_if_t<(n>2)>>
class MyClass {

// ...

(the gratuitous use of parenthesis is needed to resolve some parsing ambiguities, otherwise).

If the conditions are met, the fact that the template has, formally, an extra parameter gets hardly noticed.

  • Related