我需要帮助尝试检索保存在std::list<boost::shared_ptr<boost::any>>
我正在使用私有的单例控制器类std::list
。客户端类将能够通过这个控制器类添加/删除/编辑程序使用的具体类对象。
使用的原因boost::shared_ptr
是因为我为每个创建的具体类分配了一个唯一的 objID。将实例 obj 添加到控制器后,用户将能够稍后搜索和删除 obj。每个具体类的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....
}
}