I need helping trying to retrieve data held in a


I am working on a Singleton Controller class with a private std::list. Client class(es) will be able to Add/Remove/Edit concrete class objects to be used by the program through this Controller class.

The reason for using boost::shared_ptr is because I assign a unique objID to each concrete class created. Once instance objs are added to controller, user will be able to search and remove objs later. The Add(....) and Remove(...) overloaded methods for each concrete class work fine.

I am now trying to create getObject(int index) and setObject(int index) methods but can't seem to figure out how to cast the returned pointer to a Concrete class.

Please advise.

My current code:

    //Singleton.h controller class
    static Singleton *mgr;

    typedef boost::shared_ptr<boost::any> Shapes_Ptr;
    //private static list
    static std::list<Shapes_Ptr> shapes; 

    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


    //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);
                else { ++cc; }

    //Edit Shape
    Shapes_Ptr EditObject( const int index )
        //same code as getObject()...


    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....

Edited by badboy11: n/a

6 Years
Discussion Span
Last Post by firstPerson

I'm not too familiar with boost::any, but do you have to any_cast to a boost::any? Or can you just use the object directly? That is if ( boost::any_cast<boost::any> (contrl->getObject(i)).type() == typeid(Physics::Box2D) ) vs if ( contrl->getObject(i).type() == typeid(Physics::Box2D) ) Also, you can see if the cast is failing with:

        any_cast<some type>(yourobject);
        cout << "success";
    catch(const boost::bad_any_cast &)
        cout << "failure";

You should definitely make sure this cast succeeds:

any_cast<Box2D> (contrl->getObject(i) )

before calling .Info() on the result.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.