0

我需要帮助尝试检索保存在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....
    }
}
4

1 回答 1

0

撇开您当前代码的特定问题不谈,我认为您的设计存在问题。

您有这个单例管理器类,它充当一种池,并且正如您所说,为每个对象分配唯一的 ID,以便以后可以找到它们。但是你知道是什么让代码找到对象吗?指点!如果您使用普通池,每个类型层次结构一个(因此不再有任何 Boost Any),您可能会发现它同样有用,并且会减少令人讨厌的 if/else typeid 检查代码(每个人都会同意这不是一个好的用途) RTTI,除了糟糕的 OOP 之外)。

你认为呢?如果你想从一个中心位置分配你的对象,请使用 Boost Pool,并使用指针作为你的唯一 ID,从而避免一路上的查找。

于 2012-02-09T23:18:38.323 回答