函数指针和函子
函数指针是函子吗?是否有正在使用的虚拟函子可以帮助同级函子进行静默编译?
Are function pointers functors ? Is there a virtual functor in use that helps sibling functors compile silently ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
至少正如该术语通常在 C++ 中使用一样(警告:相对于 Haskell 等其他语言,它的使用完全不同),函子是一个重载
operator()
因此它可以像函数一样被调用。由于它们使用相同的语法,因此可以编写模板来交替接受指向函数的指针或函子实例。然而,并非所有算法都会这样做 - 有些算法期望(例如)您为
argument_type
和result_type
等内容提供带有typedef
的内容。标准库提供了几个类(unary_function
和binary_function
),用作函子的基类来提供这些功能。如果您愿意,您可以自己提供它们——这些基类纯粹是为了方便(有些人觉得它们不是特别方便)。At least as the term is normally used in C++ (Warning: it's used entirely differently relative to other languages such as Haskell), a functor is a class (or an instance of a class) that overloads
operator()
so it can be invoked like a function.Since they use the same syntax, a template can be written to accept either a pointer to a function or an instance of a functor interchangeably. Not all algorithms will do so however -- some expect (for example) that you supply something with
typedef
s for things likeargument_type
andresult_type
. The standard library provides a couple of classes (unary_function
andbinary_function
) to use as base classes for your functors to supply these. You can supply them on your own if you prefer -- these base classes are purely for convenience (and some people don't find them particularly convenient).函数指针是实际函数的地址。仿函数是一个已经重载了operator()的类;这些类的实例可以使用与函数相同的语法传递和调用。所以不,函数指针不是函子。
我不知道什么是“虚拟函子”或“兄弟函子”,所以我无法回答你的第二个问题。
A function pointer is the address of a real function. A functor is a class for which the
operator()
has been overloaded; instances of these classes can be passed around and called with the same syntax as a function. So no, function pointers are not functors.I don't know what "virtual functors" or "sibling functors" are, so I can't answer your second question.