Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requires-clause appears after template template parameter: is this legal grammar?

Recently, I unexpectedly found that gcc and msvc accept the following code (notice the requires-clause in template-list):

#include <vector>

template <template <class> requires true class>
void f() {}

int main() {
  f<std::vector>();
}

and clang rejects its grammar with:

<source>:3:28: error: template template parameter requires 'class' after the parameter list
template <template <class> requires true class>
                           ^

Which compiler should I trust? Is this code grammatically valid?

like image 489
康桓瑋 Avatar asked Apr 04 '21 16:04

康桓瑋


People also ask

Why do you need the requires clause?

A requires clause uses a compile-time Boolean expression to define requirements on template arguments or function declarations. It affects the behavior of a program, determining whether a function participates in overload resolution or not or whether a template instantiation is valid.

Why do we use template template parameter?

Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

What is require in C++?

template<typename T> requires { requires Eq<T>; } void f(T a, T b); Here, the 2nd requires is called a nested-requirement; it evaluates its expression (other code in the block of the requires-expression is not evaluated). I think this is way worse than the status quo. Now, you get to write requires twice everywhere.


1 Answers

Yes, this appears to be legal grammar. A template begins with a template-head which is

template < template-parameter-list > requires-clause opt

then a template-parameter-list can be

template-parameter

where template-parameter can be

type-parameter

and then type-parameter can be

template-head type-parameter-key ...optidentifieropt

Now this includes template-head which allows for a requires-clause as mentioned above.

like image 171
cigien Avatar answered Oct 25 '22 19:10

cigien