C++ 需要用于检查函数签名的表达式不适用于 Lambdas 或 gcc 中的成员函数

C++ Requires expression for checking function signature does not work for Lambdas or member functions in gcc

C++20 要求可以使用表达式来检查特定函数或类型是否存在,例如在模板参数中并在概念中使用。

在下面的代码片段中,我使用 requires 表达式来检查函数的签名。 对于 lambda 和定义的函数,我希望 requires 表达式的计算结果为 true。 但是,对于 lambda 表达式,该表达式失败。 为什么会这样?

int func(int a) noexcept { return 1; }

int main() {
  auto lam = [](int a) noexcept -> int { return 1; };
  // works fine for a function with this signature: 
  static_assert(requires(int a) {  { func(a) } ->std::same_as<int>;  });
  // the following three conditions each evaluate to false for the lambda
  static_assert(requires(int a) {
    lam(a);
    {lam(a)}->std::same_as<int>;
    requires std::is_same_v<decltype(lam(a)), int>;
  });
  return 0; 
}

同样适用于任意成员函数:

struct T { void f() noexcept; };

int main() {
  static_assert(requires(T o) {    o.f();  });
}

在 gcc-10.0 和 gcc-trunk 上编译,代码片段在 compiler explorer.

上可用

这是 GCC 中的一个错误,is now fixed 用于 gcc 10.0 的发布。