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