在C ++中奇怪使用[]。发生什么事? [英] Strange use of [] in C++. What is happening?
问题描述
首先,这不是关于数组或operator []重载的一个虚拟问题!
First of all, this is not a dummy question about arrays or operator[] overload!
我试图编译Qt Creator,但我收到此方法中的错误:
I was trying to compile Qt Creator and I've received an error in this method:
static QList<IDocumentFactory*> getNonEditorDocumentFactories()
{
return ExtensionSystem::PluginManager::getObjects<IDocumentFactory>(
[](IDocumentFactory *factory) {
return !qobject_cast<IEditorFactory *>(factory);
});
}
错误是:
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
我知道我做错了编译Qt Creator,可能是g ++版本,但问题不是这样。
I know that I'm doing something wrong to compile Qt Creator, probably g++ version, but the question is not that.
我想理解这段代码,因为对于我这种使用 []
在语法上不正确。可以有人请解释一下这里发生了什么。
I would like to understand this code because for me this use of []
is syntactically incorrect. Can someone please explain me what is happening here.
推荐答案
这是一个lambda函数。它在C ++ 11中引入。您可以访问 http://en.cppreference.com/w/cpp/language获取更多详情/ lambda 。
That's a lambda function. It was introduced in C++11. You can get more details at http://en.cppreference.com/w/cpp/language/lambda.
如果您不能使用lambda函数,C ++ 03中的等效代码为:
If you are not in a position to use a lambda function, the equivalent code in C++03 would be:
struct MyFunctor
{
bool operator()(IDocumentFactory *factory) const
{
return !qobject_cast<IEditorFactory*>(factory);
}
};
static QList<IDocumentFactory*> getNonEditorDocumentFactories()
{
return ExtensionSystem::PluginManager::getObjects<IDocumentFactory>(MyFunctor());
}
你也可以在C ++ 11中使用上面的代码,在c ++ 11中使用lambda函数。
You can use the above in C++11 too but it is more idiomatic to use a lambda function in c++11.
这篇关于在C ++中奇怪使用[]。发生什么事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!