Search code examples
c++c++20c++-conceptsnon-type-template-parameter

Non-type template parameters and requires


I am learning concepts, and I can not figure out a way to restrain the value (not type) of non-type template parameter.

Example of code that compiles, although I wish it did not(due to failed requirement):

#include <cassert>

enum Bla{
    Lol, 
    Haha
};

template<Bla b>
requires requires{
    // my guess is that this just checks that this is valid expression, not
    // that it is true
    b>1; 
}
void f(){
    assert(b>1);
}

int main() {
    f<Lol>(); // compiles, not funny ;)
}

Note: this is simplified example( I want "template overloading") so static_assert is not good for me, and I am trying to avoid std::enable_if since syntax is hideous.


Solution

  • If you only have a boolean condition and nothing else, do this:

    template<Bla b>
    requires(b > 1)
    void f() {}
    

    Alternative longer syntax, if you need to check more things in the same requires-expression:

    template<Bla b>
    requires requires
    {
        requires b > 1;
    //  ^~~~~~~~
    }
    void f() {}