我試圖使用std::vector<T*>::push_back
與std::mem_fun
和std::binder1st
,但它似乎不可行,可以這樣做嗎?使用std :: vector <T*> :: push_back與std :: mem_fun和std :: bind1st
我試着用下面的代碼來舉例說明。
#include <vector>
#include <functional>
#include <iostream>
using namespace std;
struct A {
int _Foo;
virtual int AFoo() { return _Foo; };
};
struct B: public A {
int BFoo(int bar) { return _Foo+bar ; };
};
struct C: public A {
int CFoo() { return --_Foo; };
};
class MyContainer
{
static const int MyArraySize = 100;
A* MyArray[MyArraySize];
public:
MyContainer() {
int half = MyArraySize/2;
for(int i=0; i< half; ++i)
MyArray[i] = new B;
for(int i=half; i < MyArraySize; ++i)
MyArray[i] = new C;
}
template<class T, class Fn1>
int Execute(Fn1 func)
{
int count = 0;
for(int i=0; i< MyArraySize; ++i){
T* t = dynamic_cast<T*>(MyArray[i]);
if(t)
{
func(t);
++count;
}
}
return count;
}
template<class T, class Res, class Arg>
int Execute(mem_fun1_t<Res, T, Arg> func, Arg argument)
{
return Execute<T>(binder2nd< mem_fun1_t<Res,T,Arg> >(func, argument));
}
template<class T>
vector<T*> GetItems() // <-- This is the problem function
{
vector<T*> ret;
Execute<T>(bind1st(mem_fun(&vector<T*>::push_back), ret));
return ret;
}
};
int main(int argc, char* argv[])
{
MyContainer cont;
cont.Execute<B>(mem_fun(&B::BFoo), 10);
cont.Execute<C>(mem_fun(&C::CFoo));
vector<B*> v = cont.GetItems<A>(); // <-- the problem function is called here.
cout << "v.size = " << v.size() << endl;
}
我的目標是具有容器類,我可以告訴它執行功能接收所選擇的項目(「A」的物體或「A」衍生物對象)作爲參數。但我沒有設法使用std::vector::push_pack
。
該錯誤是一個錯字創建的例子,但謝謝! Boost現在不是真正的選擇。 =/ – Vargas 2010-08-19 19:38:57
您始終可以滾動您自己的bind1st函數和binder1st結構。只需複製它們的實現,但將const T&t更改爲T t。這樣你就不會以雙引用結束。 – 2010-08-20 13:34:07
謝謝,好主意! – Vargas 2010-08-20 19:16:21