首页 > 解决方案 > C++ 需要用于检查函数签名的表达式不适用于 Lambda 或 gcc 中的成员函数

问题描述

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

在下面的代码片段中,我使用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 上编译的代码片段可在编译器资源管理器上找到。

标签: c++lambdac++20c++-concepts

解决方案


这是 GCC 中的一个错误,现在已在 gcc 10.0 版本中修复。


推荐阅读