Ali*_*Ali 2 c++ templates stl functor
我想run打电话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;
}
Run Code Online (Sandbox Code Playgroud)
这不编译,错误消息对我没有帮助:
at f():
无法匹配'(std :: binder1st <std :: mem_fun_t <void,Car >>)()'
在运行调用时:
'class std :: mem_fun_t <void,Car>'中
没有名为'first_argument_type'的类型'class std :: mem_fun_t <void,Car>'中没有名为'second_argument_type'的类型
请不要提升.
更新:即使问题解决了,我也很高兴看到TR1/C++ 0x解决方案!
bind1st从二元函数和值中生成一元函数.您正在尝试创建一个不使用一元函数的参数的函数,并且在标准C++ 03中没有任何东西可以支持它.
你必须做这样的事情.
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;
}
Run Code Online (Sandbox Code Playgroud)
使用lambdas的C++ 0x解决方案 - 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;
}
Run Code Online (Sandbox Code Playgroud)