简体   繁体   English

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

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

A c++20 requires expression can be used in order to check whether specific functions or types exist eg in a template argument and used in a concept.可以使用 c++20 requires 表达式来检查特定的函数或类型是否存在于例如模板参数中并在概念中使用。

In the code snipplet below I use a requires expression in order to check the signature of a function.在下面的代码片段中,我使用了一个requires表达式来检查函数的签名。 I expected the requires expression to evaluate to true both for the lambda and for the defined function.我期望requires表达式对于 lambda 和定义的函数都评估为true The expression fails for the lambda expression though.尽管 lambda 表达式的表达式失败。 Why that is the case?为什么会这样?

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; 
}

The same applies for arbitrary member functions:这同样适用于任意成员函数:

struct T { void f() noexcept; };

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

Compiled on gcc-10.0 and gcc-trunk, the code snipplet is available on compiler explorer .在 gcc-10.0 和 gcc-trunk 上编译,代码片段在compiler explorer上可用。

这是 GCC 中的一个错误,现在已针对 gcc 10.0.0 版本修复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写一个 C++ 需要表达式来查找具有 arguments 的特定成员函数/静态函数? - How do I write a C++ requires expression that looks for specific member functions/static functions with arguments? C ++模板机制获取函数参数的数量,这将适用于lambdas和普通函数 - C++ template mechanism to get the number of function arguments, which would work for lambdas and normal functions 检查具有给定签名的函数在C ++中是否存在 - Checking if a function with a given signature exists in c++ c++ 模板成员 function 使用 lambda 时的实例化 - c++ template member function instantiation when using lambdas C++ typedef 成员函数签名语法 - C++ typedef member function signature syntax 带有lambdas作为参数的C ++函数 - C++ Functions with lambdas as arguments 将成员函数和lambdas都传递给std :: function - Passing both member functions and lambdas to std::function C ++继承相同类型签名的成员函数(阴影) - C++ inheriting member functions of the same type signature (shadowing) c++ class 成员 function 指针在 ZA2F2ED4F8EBC2CBB4C21A29DC40AB61ZD 中无法正常工作 - c++ class member function pointer does not work rightly in class 链接器是否可以报告未使用的成员函数? (C ++)(GCC) - Can unused member functions be reported by the linker? (C++)(gcc)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM