What is the simplest way to “cast” a member function pointer to a function pointer in C++?

匆匆过客 提交于 2019-12-10 16:13:30

问题


I want to provide a member function for the "comp" parameter of an STL algorithm like lower_bound( ..., Compare comp ). The comp() function accesses a non-static member field so it must itself be a non-static member but the type of a non-static member function pointer is different from that of an ordinary function pointer.

What is the best way around this problem?


回答1:


This is the most common use of std::mem_fun and std::mem_fun_ref. They're templates that create functors that invoke the specified member function. TR1 adds an std::tr1::bind that's also useful and more versatile (and if you don't have TR1 available, that's based on Boost::bind). C++0x will include std::bind in the standard library (virtually unchanged from TR1).




回答2:


It sounds like you want something like boost::bind, to bind the member function pointer to a instance of that class.

Would you care to elaborate your question a bit as to what you're trying to do? Example code, etc.?




回答3:


#include<tr1/functional>

and use mem_fn()



来源:https://stackoverflow.com/questions/3287096/what-is-the-simplest-way-to-cast-a-member-function-pointer-to-a-function-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!