Why would one use function pointers to member method in C++?

前端 未结 10 2156
情书的邮戳
情书的邮戳 2021-02-10 23:48

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 functio

10条回答
  •  借酒劲吻你
    2021-02-11 00:31

    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))
    

提交回复
热议问题