为什么lambda会返回bool?

时间:2017-12-13 08:07:35

标签: c++ qt c++11 return return-type

我开始学习C ++ 11和C ++ 14,我有一个问题。为什么lambda不会返回23?

template<class T>
auto func(T t)
{
    return t;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    auto abc = []()->auto { return func(23); };
    qDebug() << abc; // output: true

    return a.exec();
}

2 个答案:

答案 0 :(得分:15)

@Bathsheba指出。你有一个错字,不要打电话给lambda。现在,很明显operator<< qDebug()没有在lambda的闭包类型上重载。因此,必然会发生隐式转换序列。唯一可用的,只是因为你的lambda是无捕获的,首先是转换为函数指针。

现在,which overload of operator<<可用于打印函数指针吗?从表面上看,有两个可能的候选人:

operator<<(bool t)         // Because it prints true, duh
operator<<(const void *p)  // Because pointers :)

为什么bool超载?因为函数指针不能隐式转换为void*。有条件地支持该转换,并且必须使用强制转换([expr.reinterpret.cast]/8)执行:

  

将函数指针转换为对象指针类型,反之亦然   有条件支持。

只留下[conv.bool]

  

算术,无范围枚举,指针或指针的prvalue   成员类型可以转换为bool类型的prvalue。

答案 1 :(得分:10)

你需要实际执行 lambda:

qDebug() << abc();

目前<<重载正在将lambda的类型转换为bool,并输出该值。