sudo rm -rf slash
sudo rm -rf slash

Reputation: 1254

When does "requires" cause a compiler error

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.

Upvotes: 2

Views: 371

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473407

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.

Upvotes: 3

Related Questions