2014-06-18 83 views
2

假设我想拥有一些向量,每个向量包含不同类型的对象, 是否有任何方法将指针映射到它们? 事情是这样的:映射不同类型的向量指针

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>; 

我大概可以使用自定义的类与向量指针作为成员,这从一个共同的基类派生。然后,我将它们贬低为所需的类并检索指针,但我想查看是否有更好的选项。

+0

你知道在编译时Class1的...... N级?或者你在寻找一个完全通用的解决方案? – quantdev

+0

@quantdev你能详细说一下吗?它应该适用于任何职业,如果这就是你的意思。 – Veritas

回答

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; 
    } 
} 
+0

我认为这是我正在寻找的。我会使用type_index进行映射,但由于某些原因,从void *投射并没有发生在我身上! – Veritas

+0

@Veritas我实际上正在尝试它在这里工作,但我似乎无法做到。这个例子肯定有很多错误 –

+0

可能有,我没有检查。这是我喜欢的方法。 – Veritas