4

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?

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
zoo
  • 1,901
  • 1
  • 17
  • 25

3 Answers3

7

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

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • mem_fun() works only with functions having one or no parameter, whereas comp must point to a function with two parameters. Is this functionality available in Qt? – zoo Jul 20 '10 at 06:30
  • `mem_fun` also doesn't work with functions that have reference parameters :( If you use `mem_fun_ref` and then try to combine it with `bind1st` or `bind2nd`, it fails again because they are just broken. I recommend to completely change to `boost::bind` and `boost::function` – Johannes Schaub - litb Jul 20 '10 at 09:59
  • For those who are coming late to this page, like me: avoid using `mem_fun` and `mem_fun_ref` which are deprecated; switch to `mem_fn`. *Details:* http://stackoverflow.com/questions/11680807/stdmem-fun-vs-stdmem-fn – legends2k Dec 30 '12 at 15:24
  • Or even better, in the OP's case, use a lambda function. – legends2k Dec 30 '12 at 15:28
6

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.?

Thanatos
  • 42,585
  • 14
  • 91
  • 146
1
#include<tr1/functional>

and use mem_fn()

zoo
  • 1,901
  • 1
  • 17
  • 25