Миш*_*сим 3 c++ qt return return-type c++11
我已经开始学习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();
}
Run Code Online (Sandbox Code Playgroud)
Sto*_*ica 15
正如@Bathsheba指出的那样.你有一个错字,不要打电话给lambda.现在,很明显,operator<<对于qDebug()lambda的闭包类型没有重载.因此,必然会发生隐式转换序列.唯一可用的,只是因为你的lambda是无捕获的,首先是转换为函数指针.
现在,哪个重载operator<<可用于打印函数指针?从表面上看,有两个可能的候选人:
operator<<(bool t) // Because it prints true, duh
operator<<(const void *p) // Because pointers :)
Run Code Online (Sandbox Code Playgroud)
那么为什么bool过载呢?因为函数指针不能隐式转换为void*.有条件地支持该转换,并且必须使用强制转换([expr.reinterpret.cast]/8)执行:
有条件地支持将函数指针转换为对象指针类型(反之亦然).
这只留下了[conv.bool]:
算术,无范围枚举,指针或指向成员类型的指针的prvalue可以转换为bool类型的prvalue.
Bat*_*eba 10
你需要实际执行 lambda:
qDebug() << abc();
Run Code Online (Sandbox Code Playgroud)
目前,<<重载是将lambda 的类型转换为a bool,并输出它.