0

に保持されているデータを取得しようとするのを手伝う必要がありますstd::list<boost::shared_ptr<boost::any>>

private を持つ Singleton Controller クラスに取り組んでいますstd::list。クライアント クラスは、この Controller クラスを介して、プログラムで使用される具体的なクラス オブジェクトを追加/削除/編集できます。

使用する理由boost::shared_ptrは、作成した各具象クラスに一意の objID を割り当てるためです。インスタンス obj がコントローラに追加されると、ユーザーは後で obj を検索して削除できるようになります。各具象クラスのAdd(....)およびオーバーロードされたメソッドは正常に機能します。Remove(...)

getObject(int index)&メソッドを作成しようとしてsetObject(int index)いますが、返されたポインターを Concrete クラスにキャストする方法がわかりません。

お知らせ下さい。

私の現在のコード:

//===============================================================
//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を割り当てます。しかし、コードがオブジェクトを見つけられるようにするものを知っていますか?ポインタ!タイプ階層ごとに1つずつ(したがってBoost Anyがない)通常のプールを使用する場合、それは同じように役立つことがあり、typeidチェックコード(誰もが同意するだろう)はあまり厄介ではありません。貧弱なOOPであることを除いて、RTTIの)。

それで、あなたは何と言いますか?これをチャックし、中央の場所からオブジェクトを割り当てるために何かが必要な場合はBoost Poolを使用し、一意のIDとしてポインターを使用して、途中でのルックアップを回避します。

于 2012-02-09T23:18:38.323 に答える