I would like to write a ServiceLocator design pattern class in C++. The aim is to provide three methods :
CServiceLocator::push(obj); CServiceLocator::get<IObjType>(); CServiceLocator::getAll<IObjType>(); I prefer keep a reference instead of pointers of objects. So I would like to use a std::vector of references objects. In order to do that, I make a std::vector but I can't compile and I see on the web that I can't cast a reference into a (void*).
Here is the code of my class :
class CServiceLocator { public: virtual ~CServiceLocator(){} template <class T> static void push(T &object) { m_objectList.push_back((void*)object); } template <class T> static T & get() { for (std::vector<void*>::iterator it = m_objectList.begin(); it != m_objectList.end(); it++) { //on essaie de faire un dynamic cast pour trouver le premier objet du bon type try { T & obj = (T&)dynamic_cast<T>(*it); return obj; } catch (std::bad_cast &) { //il n'est pas du bon type } } } template <class T> static std::vector<T&> & getAll() { std::vector<T&> result; for (std::vector<void*>::iterator it = m_objectList.begin(); it != m_objectList.end(); it++) { //on essaie de faire un dynamic cast pour trouver les objets du bon type try { T & obj = (T&)dynamic_cast<T>(*it); result.push_back(obj); } catch (std::bad_cast &) { //il n'est pas du bon type } } return result; } private: CServiceLocator() {} static std::vector<void*> m_objectList; }; Here is a usage example of expected result
A a; B b; CServiceLocator::push<A>(a); CServiceLocator::push<B>(b); A &a1 = CServiceLocator::get<A>(); Any one has idea on how to do that ?
A a();does not create an object. It declares a function nameda, which returns an object of typeA, and takes no arguments. To create an object using the default constructor, leave off the parens. i.e.A a;orB b;