Code:
#include <functional>
#include <string>
#include <iostream>
using namespace std;
#pragma warning(disable:4786)
template<class R, class T, class A1, class A2>
struct mem_fun2_t : public binary_function<A1, A2, R> {
R(T::*pmem)(const A1&,A2) const;
mem_fun2_t() { pmem = NULL;}
mem_fun2_t(R (T::*pm)(const A1&, A2) const)
{pmem = pm; }
mem_fun2_t<R,T,A1,A2>::result_type operator()(T& t, const mem_fun2_t<R,T,A1,A2>::first_argument_type a, mem_fun2_t<R,T,A1,A2>::second_argument_type b)
{ return (t.*pmem)(a,b); }
};
template <class R, class T, class A1, class A2>
mem_fun2_t<R,T,A1,A2> mem_fun2(R (T::*fp)(const A1&,A2) const)
{ return mem_fun2_t<R,T,A1,A2>(fp); }
int main()
{
char c;
string str("Hello, world");
string comma(",");
mem_fun2_t<string::size_type, string, string, string::size_type> pfun;
// Ask user which way to search
cout<<"Search in reverse(Y/N)?";
c = cin.get();
// set up member function pointer accordingly
if ( c == 'Y' )
{
pfun = mem_fun2<string::size_type, string, string,string::size_type>(&string::find_last_of);
}
else
{
pfun = mem_fun2<string::size_type, string, string,string::size_type>(&string::find_first_of);
}
// use the object
string::size_type pos = pfun(str, comma, 0); // but the third param must be str.size() if you search in reverse!!!
if ( pos == string::npos )
cout<<"Not found"<<endl;
else
cout<<"Found at pos: "<<pos<<endl;
return 0;
}