在c++中保持引用对象的向量

Keep a vector of reference objects in C++

本文关键字:对象 向量 引用 c++      更新时间:2023-10-16

我想用c++写一个ServiceLocator设计模式类。目的是提供三种方法:

CServiceLocator::push(obj);
CServiceLocator::get<IObjType>();
CServiceLocator::getAll<IObjType>();

我更喜欢保存对象的引用而不是指针。所以我想使用std::vector的引用对象。为了做到这一点,我做了一个std::vector,但我不能编译,我在网上看到我不能将引用强制转换为(void*)。

下面是我的类的代码:
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;
};

下面是预期结果

的用法示例
A a;
B b;
CServiceLocator::push<A>(a);
CServiceLocator::push<B>(b);
A &a1 = CServiceLocator::get<A>();

有人知道怎么做吗?

不能直接创建引用的std::vector

如果你想完成类似的事情,你有两个选择:

  • 使用指针,以某种方式验证这些指针永远不会是nullptr
  • std::reference_wrapper