在c++中保持引用对象的向量
Keep a vector of reference objects in C++
我想用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
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 从多个源构造一个对象,包括一个对象向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 对象 C++ 向量的 STL 容器
- 初始化C++中的对象向量
- 从自定义类获取对象向量中的 max 元素
- 如何在 c++ 中打印存档中的对象向量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何在C++中打印对象向量的内容
- 打印出对象向量中的每个元素C++
- 在 c++ 的构造函数中分配对象向量时出错
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 对象向量是否在堆或堆栈上分配C++?
- 基于不同字段的对象向量的排序功能
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 用rapidjson读取子对象向量
- 尝试使用比较运算符对对象向量进行排序
- 如何用对象向量重载 cin(>>)
- 如何将某个元素从shared_ptr擦除到对象向量?