Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return nullptr from a lambda function?

Tags:

c++11

lambda

I have a small lambda function which shall find and return a QTreeWidgetItem. But if it does not find the given item, then it shall return a nullptr. But if I try to compile it then it gives me an error.

The function:

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.
};

The error:

Error 1 error C3487: 'nullptr': all return expressions in a lambda must have the same type: previously it was 'QTreeWidgetItem *' cpp 251

I changed the mentioned line with this and now it compiles:

return (QTreeWidgetItem*)( nullptr );

but I would like to avoid this syntax. How can I solve this ?

I use Visual Studio 2012.

like image 637
p.i.g. Avatar asked Jun 11 '15 14:06

p.i.g.


1 Answers

You can add an explicit return type annotation:

auto takeTopLevelItem = []( ... ) -> QTreeWidgetItem*
{
    // ...
}

That way nullptr will be converted to your pointer type properly. You're getting that error because the lambda assumes no conversions should be made, and treats nullptr_t as a legitimate alternative return type.


As a side note, consider using (std::)optional instead. The nullability of pointers can be used to represent a missing return, but it doesn't mean it necessarily should be.

like image 129
Bartek Banachewicz Avatar answered Sep 23 '22 06:09

Bartek Banachewicz