【问题标题】:Why does 'std::function<void()>' take a lambda returning 'bool' without any warning?为什么 'std::function<void()>' 需要一个 lambda 返回 'bool' 而没有任何警告?
【发布时间】:2021-06-20 20:03:54
【问题描述】:
#include <functional>

void f()
{
    // warning: return-statement with a value, in function returning 'void'
    return true; 
}

std::function<void()> fn = [] { return true; }; // no warning

int main()
{}

为什么std::function&lt;void()&gt; 返回一个lambda bool 没有任何警告?

【问题讨论】:

标签: c++ function c++11 generics lambda


【解决方案1】:

因为它就是这样设计的。如果模板参数中的返回类型为void,则忽略函子的返回类型。

这与std::is_invocable_r 的工作方式一致。

此外,(非魔法)类很难发出警告。 (不像因错误而失败,这很容易。)更不用说标准没有区分警告和错误。

【讨论】:

  • 我们需要一个标准化的static_warning。有一些不可移植的方式来发出警告,使用已弃用的首选项,但所有实现的土地。
【解决方案2】:

这就是它的工作:它处理function 对象的声明类型和它所持有的可调用对象之间的阻抗匹配。

普通的函数指针是严格类型化的:

int f(double);
double g(int);

int x = f(3.2); // OK
long y = f(3);  // OK: argument and return type get converted

int (*ptr)(double);
ptr = f; // OK: f is pointer to function taking double and returning int
ptr = g; // error: types don't match

std::function 处理类型不匹配,因此类型转换看起来更像您在函数调用中所期望的:

std::function<int(double)> func;
func = f; // OK
func = g; // OK: argument and return type get converted internally

这种灵活性是有代价的,所以当您处理精确类型时,您应该使用函数指针而不是std::function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多