C++运算符 () 括号重载
我最近问了一个关于从向量中删除项目的问题。好吧,我得到的解决方案有效,但我不明白它 - 我找不到任何解释它的文档。
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;
};
用作:
hosts.erase(std::remove_if(hosts.begin(), hosts.end(), RemoveBlockedHost(blockedhost)), hosts.end());
我查看了 std::remove_if 的文档,它说仅当类重载 () 运算符时才可以传递类而不是函数。没有任何信息。
有谁知道以下链接:
- 一本包含示例/解释的书
- 或者,在线文档/教程的链接
对此提供帮助将不胜感激。我不喜欢在我的软件中添加代码,除非我理解它。我知道它有效,并且我(在某种程度上)熟悉运算符重载,但我不知道 () 运算符的用途。
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它在 C++ 中被称为函子
这个答案有一个很好的例子等
C++ 函子 - 及其用途
It's called a functor in C++
This answer has a good example etc
C++ Functors - and their uses
它是一个函数,实际上是一个函子。但常见问题解答解释了一切:
https://isocpp.org/wiki/faq/pointers-to-members#functionoids
It's a functionoid, well actually a functor. But the FAQ explains it all:
https://isocpp.org/wiki/faq/pointers-to-members#functionoids
尝试阅读有关 Functor 的更多信息 重载 Function operator() 的类称为 Functor。任何一本对 STL 有解释的不错的 C++ 书籍都会有关于它的信息。
这里是您可以参考的链接。
Try and read more about
Functors
A class that overloads the Function operator() is called a Functor. Any decent C++ book with explanation on STL will have information about it.Here is a link you may refer.
我想指出的是,在 C++11 之后,您可以使用 lambda 避免需要这样的东西:
I'd like to point out that after C++11, you can avoid needing something like this with a lambda: