1

I tried reading through some topics that might have had the answer I was looking for, but I didn't get an answer.

In any case. I have a class that holds a vector of shared_ptr's to a base (interface) class: IInputDevice.

Here is the member vector in manager class: CInputManager:

// In class: CInputManager
private:
    std::vector<std::tr1::shared_ptr<IInputDevice>> m_vecpInputDevices;

I also have a few helper functions, that is meant to retrieve a specific input device (i.e: keyboard, mouse, etc).

In this case, I have a keyboard "getter" that calls the inputmanager's GetDevice function, that returns the smart_ptr in the vector, that has the specific input type ID.

inline std::tr1::shared_ptr<CKeyboard> GetKeyboard()
{
    return CInputManager::GetInstance().GetInputDevice(CInputType::Keyboard());
}

The function is incomplete, as I need a cast of some sort, to get a

smart_ptr<CKeyboard> 

type.

Here is the "get" function in CInputManager, that searches the vector for the specific device:

std::tr1::shared_ptr<IInputDevice> CInputManager::GetInputDevice(CInputType type)
{
for( std::vector<std::tr1::shared_ptr<IInputDevice>>::iterator pDeviceIter = m_vecpInputDevices.begin();
    pDeviceIter != m_vecpInputDevices.end();
    pDeviceIter++)
{
    if( (*pDeviceIter)->GetInputType() == type )
        return (*pDeviceIter);
}

return NULL;

}

The CInputType class also has a overloaded == operator, to check only if the ID's match. Hence the

if( (*pDeviceIter)->GetInputType() == type )
        return (*pDeviceIter);

So, I'd love to hear from you guys if you have a smart, simple cast/solution to this problem, as you can notice that I'd like helper functions to retrieve a specific device.

Thanks, and regards, Oyvind

Oyvind Andersson
  • 362
  • 6
  • 22
  • 3
    std::static_pointer_cast or std::dynamic_pointer_cast are probably what you're looking for - they're the shared_ptr equivalents of static_cast or dynamic_cast – Mike Vine Jul 13 '13 at 20:48
  • 1
    here is a topic that will help you. http://stackoverflow.com/questions/1358143/downcasting-shared-ptrbase-to-shared-ptrderived?rq=1 – Gabriel Jul 14 '13 at 09:27
  • Thank you both! Got what I was looking for, but avoided dynamic casting all together with containers. But, first comment is correct and worked. – Oyvind Andersson Jul 16 '13 at 22:38

0 Answers0