1
如何实现一个非常简单的boost :: bind版本,它不绑定参数,但提供了一种方法来调用C++类中的成员函数。使用绑定类似功能调用成员函数
这是我第一次尝试:
#include <iostream>
struct Foo {
void x(int i) { std::cout << "Foo " << i << std::endl; }
};
struct Bar {
void y(int i) { std::cout << "Bar " << i << std::endl; }
};
template<typename A1, typename I, typename M>
struct Binder {
Binder(I i, M m) : i_(i), m_(m) { }
void operator()(A1 a1) {
(i_->*m_)(a1);
}
I i_;
M m_;
};
template<typename A1, typename I, typename M>
Binder<A1, I, M> my_bind(I i, M m) {
return Binder<A1, I, M>(i, m);
}
int main(int argc, const char *argv[])
{
Foo foo;
Bar bar;
Binder<int, Foo*, void (Foo::*)(int)> b1 = my_bind<int>(&foo, &Foo::x);
Binder<int, Bar*, void (Bar::*)(int)> b2 = my_bind<int>(&bar, &Bar::y);
b1(1);
b2(2);
return 0;
}
上面的实现执行工作,并将打印:
Foo 1
Bar 2
的问题是,my_bind两所调用返回不同类型的对象。我怎样才能改变程序,使my_bind将返回一个只取决于A1的类型。
我想你最好使用'std :: mem_fn()'。 ...或者你是否愿意绑定参数,例如对象? –
我已经开始着手这方面的工作,因为需要它在嵌入式应用程序中,其中C++环境不支持异常或标准库。所以,std :: men_fn在我的目标系统上不是aviable ... – Allan
当我想到这个时,它更多的是boost ::函数实现我需要了解 – Allan