Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading