为什么 std::invocable 概念阻止此代码编译

Why is std::invocable concept blocking this code from compiling

我不明白为什么在以下代码中 lambda 和函数都没有被识别为 std::invocable 兼容类型:

#include <concepts>
#include <iostream>

void f( std::invocable auto callback)
{
    callback(47);
}

void function_callback(int i)
{
    std::cout << i << std::endl;
}

auto lambda_callback = [](int i )
{
    std::cout << i << std::endl;
};

int main(int) 
{
    f(&function_callback);
    f(lambda_callback);
}

我正在使用启用了 -std=c++2a 标志的 GCC 主干。

如果你看invocable (or in the standard的定义):

template< class F, class... Args >
concept invocable =
  requires(F&& f, Args&&... args) {
    std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
      /* not required to be equality preserving */
  };

这意味着什么:

void f( std::invocable auto callback)

如果我们把它写成长格式可能会更清楚:

template <typename F>
    requires std::invocable<F>
void f(F callback);

F 是否可以使用 无参数调用 - 它是一个空函数(Args... 在这里是一个空包)。您的函数和 lambda 都不是零函数 - 它们都是一元的,因此约束正确地拒绝了它们。

您可能想要的是:

void f( std::invocable<int> auto callback)

检查 callback 是否可以使用 int.

类型的单个参数调用