Home > Mobile >  When does "requires" cause a compiler error
When does "requires" cause a compiler error

Time:11-19

Consider this code:

struct Bad {};

int main() {
    static_assert(requires(int n, Bad bad) { n  = bad; });
}

Compiling with Clang 13 and -std=c 20, I get the following error:

<source>:5:48: error: invalid operands to binary expression ('int' and 'Bad')
    static_assert(requires(int n, Bad bad) { n  = bad; });
                                             ~ ^  ~~~
1 error generated.

But I would have expected the requires expression to return false and fail the static_assert.

If I rewrite this concept as a template constraint, I get the conditional compilation that I expect i.e. the compiler doesn't complain that there is no operator = and the requires returns false.

CodePudding user response:

A notation from the standard:

If a requires-expression contains invalid types or expressions in its requirements, and it does not appear within the declaration of a templated entity, then the program is ill-formed.

So requires only gains this capability when it is in a template.

  • Related