如何从lambda函数返回nullptr?

p.i*_*.g. 9 lambda c++11

我有一个小的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.
};
Run Code Online (Sandbox Code Playgroud)

错误:

错误1错误C3487:'nullptr':lambda中的所有返回表达式必须具有相同的类型:以前它是'QTreeWidgetItem*'cpp 251

我用这个改变了提到的行,现在它编译:

return (QTreeWidgetItem*)( nullptr );
Run Code Online (Sandbox Code Playgroud)

但我想避免这种语法.我怎么解决这个问题?

我用Visual Studio 2012.

Bar*_*icz 13

您可以添加显式返回类型注释:

auto takeTopLevelItem = []( ... ) -> QTreeWidgetItem*
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这种方式nullptr将正确转换为您的指针类型.您收到该错误是因为lambda假定不应进行任何转换,并将其视为nullptr_t合法的替代返回类型.


作为旁注,请考虑使用(std::)optional.指针的可空性可用于表示缺失的回报,但并不意味着它必然应该是.

  • 我不同意关于`optional`的最后一点:`Qt`中的大多数东西都是通过指针传递的,我相信这个lambda的结果会传递给`Qt`.而且,最好遵循他们的风格,即使它在现代C++中可能是邪恶的. (4认同)