指向任意类型的std :: vector的指针(或任何其他模板化类) [英] pointer to std::vector of arbitrary type (or any other templated class)
问题描述
让我们说我想要一个指向std :: vector的指针的成员变量,但是我不想指定它存储什么类型的变量.我只想访问独立于其实际泛型类型的那些函数. C ++有可能吗?像这样的东西:
let's say i want to have a member variable for a pointer to std::vector but i do not want to specify what type of variable it stores. I want to access only those functions that are independant of it's actual generic type. is this possible with c++? something like this:
class Foo{
public:
void setVec(std::vector* someVec){
myVec = someVec;
};
int getSize(){
return myVec.size();
};
private:
std::vector* myVec;
};
int main(){
Foo foo;
vector<int> vec1;
vector<float> vec2;
foo.setVec(&vec1);
cout<<foo.getSize();
foo.setVec(&vec2);
cout<<foo.getSize();
}
注意:我不想为Foo建立模板,我只想使用具有不同类型的向量的Foo的单个实例.
note: i do not want to template Foo and i want to use only a single instance of Foo with vectors of different type.
当然-如果我可以更改类向量,则可以创建未模板化的基类
of course - if I could alter the class vector then i could create an untemplated baseclass
class Ivector{
virtual int size()=0;
};
然后创建
class vector<T> : public IVector...
从Ivector继承.但是,如果我无法更改相关类并且模板化类没有这样的非模板化基类,我该怎么办?
inherit from Ivector. but what do I do if i can't alter the class in question and the templated class does not have such an untemplated baseclass?
谢谢!
推荐答案
您几乎可以找到答案.与其让std :: vector从Ivector继承,不如创建一个新类:
You are almost at the answer. Instead of making std::vector inherit from Ivector, create a new class:
template <typename T>
class IVectorImpl : public Ivector
{
public:
explicit IVectorImpl(std::vector<T> * Data) : m_Data(Data){}
std::vector<T> * m_Data;
...
virtual int size() const {return m_Data->size();}
// Implement all the Ivector functions here to call the respective functions off of m_Data
};
现在让您的Foo类保留指向Ivector的指针,而不是std :: vector.
Now have your Foo class keep a pointer to Ivector instead of std::vector.
将Foo :: setVec模板化
Make Foo::setVec templated
template <typename T>
void setVec(std::vector<T> * vec)
{
Ivector * newVec = new IVectorImpl<T>(vec);
delete myVec;
myVec = newVec;
}
这篇关于指向任意类型的std :: vector的指针(或任何其他模板化类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!