Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if constexpr and requires-expression for ad-hoc concepts checking

Let's say, given C++17's if constexpr and Concepts TS (for instance, in recent gcc versions), we'd like to check if a type in a template function has a nested type:

#include <iostream>

struct Foo { using Bar = int; };

template<typename T>
void doSmth(T)
{
    if constexpr (requires { typename T::Bar; })
        std::cout << "has nested! " << typename T::Bar {} << std::endl;
    else
        std::cout << "no nested!" << std::endl;
}

int main()
{
    doSmth(Foo {});
    //doSmth(0);
}

The documentation for concepts is scarce, so I might have got it wrong, but seems like that's it (and the live example is on Wandbox).

Now let's consider what should happen when uncommenting the other doSmth call. It seems reasonable to expect that the requires-clause would evaluate to false, and the else branch of the if constexpr will be taken. Contrary to that, gcc makes this a hard error:

prog.cc: In instantiation of 'void doSmth(T) [with T = int]':
prog.cc:17:13:   required from here
prog.cc:8:5: error: 'int' is not a class, struct, or union type
     if constexpr (requires { typename T::Bar; })
     ^~

Is that a bug in gcc, or is that the intended behaviour?

like image 698
0xd34df00d Avatar asked Nov 06 '17 19:11

0xd34df00d


2 Answers

Concepts issue 3 ("Allow requires-expressions in more contexts") was given WP status in June. And judging by the current looks of [expr.prim.req], in particular p6:

The substitution of template arguments into a requires-expression may result in the formation of invalid types or expressions in its requirements or the violation of the semantic constraints of those requirements. In such cases, the requires-expression evaluates to false; it does not cause the program to be ill-formed.

I'd say your code is fine, and GCC hasn't implemented the resolution of issue 3 properly.

like image 104
Columbo Avatar answered Sep 28 '22 16:09

Columbo


It works starting from C++2a and gcc 10: https://wandbox.org/permlink/qH34tI6oRJ3Ck7Mm

like image 39
Dmitry Sychov Avatar answered Sep 28 '22 17:09

Dmitry Sychov