【发布时间】:2015-08-27 06:42:24
【问题描述】:
我有一个小的 lambda 函数,它可以找到并返回一个 QTreeWidgetItem。但是如果它没有找到给定的项目,那么它将返回一个nullptr。但是如果我尝试编译它,那么它会给我一个错误。
功能:
auto takeTopLevelItem = []( QTreeWidget* aTreeWidget, const QString& aText )
{
const int count = aTreeWidget->topLevelItemCount();
for ( int index = 0; index < count; ++index )
{
auto item = aTreeWidget->topLevelItem( index );
if ( item->text( 0 ) == aText )
{
return aTreeWidget->takeTopLevelItem( index );
}
}
return nullptr; // This causes a compilation error.
};
错误:
错误 1 错误 C3487:'nullptr':lambda 中的所有返回表达式必须具有相同的类型:以前是 'QTreeWidgetItem *' cpp 251
我用这个改变了提到的行,现在它编译了:
return (QTreeWidgetItem*)( nullptr );
但我想避免这种语法。我该如何解决这个问题?
我使用Visual Studio 2012。
【问题讨论】:
-
这看起来像是 VS2012 中的错误?
-
@Yakk:为什么?错误信息很清楚,不是吗?
-
@MSalters 嗯。奇怪,我其实以为只要后面的返回类型与第一个返回类型兼容(隐式可转换),一切都很好。
-
IIRC C++11 的 lambda 提案是故意保守的。为了安全起见,省略了一些相当合理的扩展。