C++ Operator() 括号重载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5503438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Operator () parenthesis overloading
提问by FurryHead
I recently asked a question about removing items from a vector. Well, the solution I got works, but I don't understand it - and I cannot find any documentation explaining it.
我最近问了一个关于从向量中删除项目的问题。好吧,我得到的解决方案有效,但我不明白 - 我找不到任何解释它的文档。
struct RemoveBlockedHost {
RemoveBlockedHost(const std::string& s): blockedHost(s) {}
// right here, I can find no documentation on overloading the () operator
bool operator () (HostEntry& entry) {
return entry.getHost() == blockedHost || entry.getHost() == "www." + blockedHost;
}
const std::string& blockedHost;
};
to be used as:
用作:
hosts.erase(std::remove_if(hosts.begin(), hosts.end(), RemoveBlockedHost(blockedhost)), hosts.end());
I looked at std::remove_if's documentation, it says that it is possible to pass a class instead of a function only when the class overloads the () operator. No information whatsoever.
我查看了 std::remove_if 的文档,它说只有在类重载 () 运算符时才可以传递类而不是函数。没有任何信息。
Does anyone know of links to:
有谁知道链接到:
- A book containing examples/explainations
- Or, a link to online documentation/tutorials
- 一本包含例子/解释的书
- 或者,指向在线文档/教程的链接
Help with this would be appreciated. I dislike adding code to my software unless I understand it. I know it works, and I am familiar (somewhat) with operator overloading, but I don't know what the () operator is for.
对此的帮助将不胜感激。我不喜欢在我的软件中添加代码,除非我理解它。我知道它有效,并且我熟悉(有点)运算符重载,但我不知道 () 运算符的用途。
采纳答案by Adam Casey
It's called a functor in C++
它在 C++ 中称为函子
This answer has a good example etc
这个答案有一个很好的例子等
回答by LumpN
It's a functionoid, well actually a functor. But the FAQ explains it all:
它是一个函数,实际上是一个函子。但常见问题解答说明了一切:
Functionoids are functions on steroids. Functionoids are strictly more powerful than functions, and that extra power solves some (not all) of the challenges typically faced when you use function-pointers.
Functionoids 是类固醇上的函数。Functionoids 严格来说比函数更强大,额外的能力解决了使用函数指针时通常面临的一些(不是全部)挑战。
https://isocpp.org/wiki/faq/pointers-to-members#functionoids
https://isocpp.org/wiki/faq/pointers-to-members#functionoids
回答by Alok Save
回答by Taywee
I'd like to point out that after C++11, you can avoid needing something like this with a lambda:
我想指出的是,在 C++11 之后,您可以避免使用 lambda 进行类似的操作:
hosts.erase(std::remove_if(hosts.begin(), hosts.end(),
[&blockedhost](HostEntry& entry) -> bool {
return entry.getHost() == blockedHost || entry.getHost() == "www." + blockedHost;
}), hosts.end());