我需要幫助試圖檢索在std::list<boost::shared_ptr<boost::any>>
如何檢索包含升壓一個std ::目錄:: shared_ptr的
我上一個Singleton Controller類的工作與私人std::list
保持數據。客戶端類將能夠通過此Controller類添加/刪除/編輯程序要使用的具體類對象。
使用boost::shared_ptr
的原因是因爲我爲每個創建的具體類分配了一個唯一的objID。一旦實例objs被添加到控制器中,用戶將能夠在稍後搜索並移除objs。每個具體類的Add(....)
和Remove(...)
重載方法工作正常。
我正在嘗試創建getObject(int index)
& setObject(int index)
方法,但似乎無法弄清楚如何將返回的指針轉換爲具體類。
請指教。
我當前的代碼:
//===============================================================
//Singleton.h controller class
private:
static Singleton *mgr;
typedef boost::shared_ptr<boost::any> Shapes_Ptr;
//private static list
static std::list<Shapes_Ptr> shapes;
public:
const Shapes_Ptr getObject(int index) const; //Return Shape
Shapes_Ptr EditObject(const int index); //Edit Shape
Info(); //Prints contents of instance to console screen
//===============================================================
//Singleton.cpp
//Return Shape
const Shapes_Ptr getObject(int index) const
{
int cc = 0;
if ((int)shapes.size() > ZERO && index < (int)shapes.size())
{
list<Shapes_Ptr>::const_iterator i;
for (i = shapes.begin(); i != shapes.end(); ++i)
{
if (cc == index)
{
return (*i);
break;
}
else { ++cc; }
}//for-loop
}
}
//Edit Shape
Shapes_Ptr EditObject(const int index)
{
//same code as getObject()...
}
//===============================================================
//main.cpp
Singleton *contrl= Singleton::Instance();
int main()
{
for (int i=0; i< 2; ++i)
{
contrl->CreateObject(Box2D());
}
for (int i = contrl->Begin(); i< contrl->End(); ++i)
{
if (boost::any_cast<boost::any> (contrl->getObject(i)).type() == typeid(Physics::Box2D))
{
//Code compiles but crashes on launch....
any_cast<Box2D> (contrl->getObject(i)).Info(); // <== ERROR CODE
}
//More if checks for other Concrete classes....
}
}
你能解釋一下你正在努力完成什麼嗎?您是否嘗試過在調試器中運行現有代碼? – 2012-02-09 22:18:42
@John - 是的,我已經在調試模式下運行了項目。我得到一個異常錯誤'bad_cast'我試圖爲私有的'std :: list'創建一個getter/setter,這樣我就可以迭代並打印出數據,並且能夠爲每個數據成員調用setter列表中的每個元素。如果有一個乾淨的或更好的暴露列表元素的方式,請告知。 – badboy11 2012-02-09 22:45:32
那麼這段代碼應該是什麼樣的?爲什麼你想要一個不知道它包含什麼類型的單例,但是包含它們呢? – 2012-02-09 22:50:07