根据类型从向量中检索对象
Retrieve object from vector based on its type
我有一个模板函数来检索对象:
template <class T>
class SystemManager {
public:
std::vector<std::shared_ptr<BaseSystem<T>>> container_;
template <template <typename> class S> // S<T> inherits from BaseSystem<T>
std::shared_ptr<S<T>> retrieve() {
return object of type S<T> from container_;
}
};
有没有办法像这样根据对象的类型检索对象?有没有办法用 std::unordered_map
来做到这一点?
一个基本的解决方案是
#define STRING 1
#define INT 2
...
vector<pair<x,y>> container;
if(container[i].first == STRING)
// do something
pair 的第一个元素是 int 类型。在将元素添加到矢量之前(假设)您已经知道它是什么类型,将它作为一对存储。
container.push_back(make_pair(TYPE, myrealdata);
另一个解决方案是
vector<MyClass> container
class MyClass
{
int type = STRING;
}
其中其他 类 继承 MyClass 并检查该值的类型。
一个解决方案是遍历 vector
并在每个元素上尝试 dynamic_pointer_cast
,return 第一个成功的。
另一种解决方案,如果可以更改容器,将使用 map
或 unordered_map
,其中 std::type_index
作为键,shared_ptr
作为价值。
我有一个模板函数来检索对象:
template <class T>
class SystemManager {
public:
std::vector<std::shared_ptr<BaseSystem<T>>> container_;
template <template <typename> class S> // S<T> inherits from BaseSystem<T>
std::shared_ptr<S<T>> retrieve() {
return object of type S<T> from container_;
}
};
有没有办法像这样根据对象的类型检索对象?有没有办法用 std::unordered_map
来做到这一点?
一个基本的解决方案是
#define STRING 1
#define INT 2
...
vector<pair<x,y>> container;
if(container[i].first == STRING)
// do something
pair 的第一个元素是 int 类型。在将元素添加到矢量之前(假设)您已经知道它是什么类型,将它作为一对存储。
container.push_back(make_pair(TYPE, myrealdata);
另一个解决方案是
vector<MyClass> container
class MyClass
{
int type = STRING;
}
其中其他 类 继承 MyClass 并检查该值的类型。
一个解决方案是遍历 vector
并在每个元素上尝试 dynamic_pointer_cast
,return 第一个成功的。
另一种解决方案,如果可以更改容器,将使用 map
或 unordered_map
,其中 std::type_index
作为键,shared_ptr
作为价值。