为什么要在C ++中使用成员方法的函数指针? [英] Why would one use function pointers to member method in C++?

查看:165
本文介绍了为什么要在C ++中使用成员方法的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多C ++书籍和教程解释如何做到这一点,但我还没有看到一个令人信服的理由选择这样做的。



我理解为什么函数指针在C中是必要的(例如,当使用一些POSIX工具时)。但是,由于this参数,AFAIK不能向它们发送成员函数。但是如果你已经在使用类和对象,为什么不使用面向对象的解决方案像functors?



真实世界的例子,你必须使用这样的函数指针,将不胜感激。



更新:我感谢大家的答案。我不得不说,虽然,这些例子没有真正说服我,这是一个有效的机制从纯OO的角度...

解决方案<函数不是先验的面向对象的(在C ++中,术语函子通常意味着一个定义了具有任意参数和返回值的运算符()可以用作实际函数或函数指针的语法插入替换)。然而,他们面向对象的问题有很多问题,首先是可用性。它只是一个很复杂的样板代码。为了像大多数对话框架一样,一个体面的信号框架,一大堆继承混乱是必要的。



实例绑定的函数指针将是非常有益的。



但是,C ++的成员函数指针满足了另一个需要。想象一下,例如,你有一个列表中有很多值,你想要执行一个方法,例如它的 print() YourType :: size 的函数指针可以帮助你,因为它可以让你写这样的代码:

  std :: for_each(lst.begin(),lst.end(),std :: mem_fun(& YourType :: print))


A lot of C++ books and tutorials explain how to do this, but I haven't seen one that gives a convincing reason to choose to do this.

I understand very well why function pointers were necessary in C (e.g., when using some POSIX facilities). However, AFAIK you can't send them a member function because of the "this" parameter. But if you're already using classes and objects, why not just use an object oriented solution like functors?

Real world examples of where you had to use such function pointers would be appreciated.

Update: I appreciate everyone's answers. I have to say, though, that none of these examples really convinces me that this is a valid mechanism from a pure-OO perspective...

解决方案

Functors are not a priori object-oriented (in C++, the term "functor" usually means a struct defining an operator () with arbitrary arguments and return value that can be used as syntactical drop-in replacements to real functions or function pointers). However, their object-oriented problem has a lot of issues, first and foremost usability. It's just a whole lot of complicated boilerplate code. In order for a decent signalling framework as in most dialog frameworks, a whole lot of inheritance mess becomes necessary.

Instance-bound function pointers would be very beneficial here (.NET demonstrates this amply with delegates).

However, C++ member function pointers satisfy another need still. Imagine, for example, that you've got a lot of values in a list of which you want to execute one method, say its print(). A function pointer to YourType::size helps here because it lets you write such code:

std::for_each(lst.begin(), lst.end(), std::mem_fun(&YourType::print))

这篇关于为什么要在C ++中使用成员方法的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆