为什么可以用具有不同返回类型的lambda构造std :: function? [英] Why can std::function be constructed with a lambda with a different return type?

查看:60
本文介绍了为什么可以用具有不同返回类型的lambda构造std :: function?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下编译正常:

#include <functional>

int main()
{
    std::function<const int&()> f = []() -> int {return 1;};
    const int& r = f(); // r is a dangling reference
    return 0;
}

怎么可能将具有const int&返回类型的std::function设置为具有int返回类型的lambda?允许这种类型的转换隐式发生而没有警告是恕我直言.

How come it's possible to set an std::function with a const int& return type to a lambda with an int return type? Allowing this sort of cast to happen implicitly and with no warning is a gotcha IMHO.

推荐答案

您可以使用任何带有相关参数可调用且其返回值可隐式转换为std::function返回值的对象来构造std::function. int可隐式转换为const int&,因此符合规则.

You can construct a std::function with any object which is callable with the relevant arguments and whose return value is implicitly convertible to the std::function return. int is implicitly convertible to const int&, so the rules are met.

编译器可以对此进行警告,但是对于一个特殊的角落情况,似乎需要做很多工作.

A compiler could feel free to warn about this, but it seems like a lot of work for a particularly corner-y corner case.

这篇关于为什么可以用具有不同返回类型的lambda构造std :: function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆