Strange use of [] in C ++. What's happening?

First of all, this is not a fictitious question about overloading arrays or operators []!

I tried to compile Qt Creator and I got an error in this method:

static QList<IDocumentFactory*> getNonEditorDocumentFactories()
{
    return ExtensionSystem::PluginManager::getObjects<IDocumentFactory>(
        [](IDocumentFactory *factory) {
            return !qobject_cast<IEditorFactory *>(factory);
        });
}

Error:

mainwindow.cpp:748: error: expected primary-expression before ‘[’ token
mainwindow.cpp:748: error: expected primary-expression before ‘]’ token
mainwindow.cpp:748: error: expected primary-expression before ‘*’ token
mainwindow.cpp:748: error: ‘factory’ was not declared in this scope

I know that I am doing something wrong to compile Qt Creator, possibly a version of g ++, but that is not the question.

I would like to understand this code because for me this use []is syntactically incorrect. Can someone please explain to me what is happening here.

+4
source share
2 answers

This is a lambda function. It was introduced in C ++ 11. You can get more information at http://en.cppreference.com/w/cpp/language/lambda .

, ++ 03 :

struct MyFunctor
{
   bool operator()(IDocumentFactory *factory) const
   {
      return !qobject_cast<IEditorFactory*>(factory);
   }
};

static QList<IDocumentFactory*> getNonEditorDocumentFactories()
{
    return ExtensionSystem::PluginManager::getObjects<IDocumentFactory>(MyFunctor());
}

++ 11, - ++ 11.

+4

:

, [] . -, , , .

++ -:

// declare lambda function and assign it to foo
auto foo = [](){
     std::cout << "hello world" << std::endl;
};

foo(); // call foo

, , getObjects < > () - .

return ExtensionSystem::PluginManager::getObjects<IDocumentFactory>(

    // this is the lambda function
    [](IDocumentFactory *factory) {
        return !qobject_cast<IEditorFactory *>(factory);
    }


); 
0

All Articles