我有一个模板函数来检索对象:
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来做?
发布于 2015-01-02 23:26:28
一种解决方案是迭代vector并对每个元素尝试dynamic_pointer_cast,返回成功的第一个元素。
如果可以更改容器,另一种解决方案是使用map或unordered_map,其中std::type_index作为键,shared_ptr作为值。
发布于 2015-01-02 23:22:47
一个基本的解决办法是
#define STRING 1
#define INT 2
...
vector<pair<x,y>> container;
if(container[i].first == STRING)
// do something其中,对的第一个元素是类型为int。在将元素添加到向量之前(假设),您已经知道它是什么类型了,并将其存储为对。
container.push_back(make_pair(TYPE, myrealdata);另一个解决办法是
vector<MyClass> container
class MyClass
{
int type = STRING;
}其他类继承MyClass并检查该值的类型。
https://stackoverflow.com/questions/27749896
复制相似问题