映射不同类型的矢量指针

时间:2014-06-18 12:35:58

标签: c++ mapping stdvector

假设我想要一些向量,每个向量包含不同类型的对象, 有没有办法将指针映射到它们? 像这样:

std::vector<class1> vec1;
std::vector<class2> vec2;
std::vector<class3> vec3;

mapper.addVectorPtr(&vec1);
mapper.addVectorPtr(&vec2);
mapper.addVectorPtr(&vec3);

std::vector<class1> * ptr1 = mapper.getVectorPtr<class1>;
std::vector<class2> * ptr2 = mapper.getVectorPtr<class2>;
std::vector<class3> * ptr3 = mapper.getVectorPtr<class3>;

我可以使用带有向量指针的自定义类作为成员,它可以从公共基类派生。然后我将它们转发到所需的类并检索指针,但我想看看是否有更好的选择。

1 个答案:

答案 0 :(得分:2)

你应该结帐http://www.cplusplus.com/reference/typeinfo/type_info/。您可以通过这种方式获取typeinfo。允许您创建一个以整数(=哈希码)作为键的映射。

然后你可以按如下方式实现你的mapclass(需要一个没有参数的构造函数)

#include <vector>
#include <typeinfo>
#include <map>
#include <iostream>

class typemap{
    std::map<unsigned long, void*> m_ptrs;
public:
    template<typename A>
    void addVectorPtr(std::vector<A>* b){
        A a;
        m_ptrs[ typeid(a).hash_code() ] = b;
    }

    template<typename A>
    std::vector<A>* getVectorPtr(){
        A a;//this is why you need the default constructor
        return (std::vector<A>*) (m_ptrs[ typeid(a).hash_code() ]);
    }
};


int main(){
    std::vector<int>* t1 = new std::vector<int>(3,3);
    typemap tm;
    tm.addVectorPtr(t1);

    std::vector<int> v=*(tm.getVectorPtr<int>());

    for(auto it = v.begin(); it!= v.end(); ++it){
        std::cout<<*it<<std::endl;
    }
}