【问题标题】:Keep a vector of reference objects in C++ [duplicate]在C ++中保留参考对象的向量[重复]
【发布时间】:2014-10-05 03:54:59
【问题描述】:

我想用 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>();

有人知道怎么做吗?

【问题讨论】:

  • A a(); 不创建对象。它声明了一个名为a 的函数,它返回一个A 类型的对象,并且不接受任何参数。要使用默认构造函数创建对象,请去掉括号。即A a;B b;
  • 你是对的,它已得到纠正,但这不是问题的目的......
  • 这就是为什么它不是一个答案,而是一个评论。

标签: c++ vector reference service-locator


【解决方案1】:

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

如果您希望完成与此类似的事情,您有两个选择:

【讨论】:

  • 我不知道 std::reference_wrapper。但是我如何使用它,因为我必须把每个对象都放在里面?我可以将 std::reference_wrapper 转换为 void* 吗?
  • Arf, std::reference_wrapper 仅适用于 c++ 11,我的目标编译器不再维护,也没有迁移到 c++ 11 ...
猜你喜欢
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 2021-02-24
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 2013-03-21
  • 2011-11-25
相关资源
最近更新 更多