开发者

How to make a functor from a member function?

开发者 https://www.devze.com 2023-02-09 23:37 出处:网络
I want run to call c.drive(): #include <functional> using namespace std; struct Car { void drive() { }

I want run to call c.drive():

#include <functional>
using namespace std;

struct Car {
    void drive() { }
};

template <typename Function>
void run(Function f) {
    f();
}

int main() {
    Car c;    
    run(bind1st(mem_fun(&Car::drive), &c));    
    return 0;
}

开发者_开发问答This does not compile and the error messages does not help me:

at f():

no match for call to ‘(std::binder1st<std::mem_fun_t<void, Car> >) ()’

at the call to run:

no type named ‘first_argument_type’ in ‘class std::mem_fun_t<void, Car>’

no type named ‘second_argument_type’ in ‘class std::mem_fun_t<void, Car>’

No boost please.

Update: even though the problem is solved, I would be very happy to see TR1/C++0x solutions!


The Boost/TR1/C++0x solution is quite straightforward:

run(std::bind(&Car::drive, &c));


bind1st makes a unary function out of a binary function and a value. You are trying to make a function that takes no parameters out of a unary function and there isn't anything to support this in standard C++03.

You will have to do something like this.

template<class X, void (X::*p)()>
class MyFunctor
{
    X& _x;
public:
    MyFunctor(X& x) : _x( x ) {}
    void operator()() const { (_x.*p)(); }
};

template <typename Function>
void run(Function f) {
    f();
}

int main() {
    Car c;
    run(MyFunctor<Car, &Car::drive>(c));
    return 0;
}


The C++0x solution using lambdas - http://www.ideone.com/jz5B1 :

struct Car {
    void drive() { }
};

template <typename Function>
void run(Function f) {
    f();
}

int main() {
    Car c;    
    run( [&c](){ c.drive(); } );    
    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消