std::vector 和多态性
#include <iostream>
#include <vector>
using namespace std;
class Base {
public:
virtual ~Base(){}
};
class Deriv : public Base {
public:
virtual ~Deriv(){}
};
void f(Base *){
cout << "f(Base *)" << endl;
}
void f(vector<Base *>){
cout << "f(vector<Base *>)" << endl;
}
int main(int argc, const char *argv[])
{
Deriv *d = new Deriv;
vector<Deriv *> v;
v.push_back(d);
f(d); // works
//f(v); // does not compile
return 0;
}
第一个 f() 有效,但第二个给出编译时错误:
f(vector
) 未找到。
我的问题:有没有办法让它工作:某种向量多态性?
#include <iostream>
#include <vector>
using namespace std;
class Base {
public:
virtual ~Base(){}
};
class Deriv : public Base {
public:
virtual ~Deriv(){}
};
void f(Base *){
cout << "f(Base *)" << endl;
}
void f(vector<Base *>){
cout << "f(vector<Base *>)" << endl;
}
int main(int argc, const char *argv[])
{
Deriv *d = new Deriv;
vector<Deriv *> v;
v.push_back(d);
f(d); // works
//f(v); // does not compile
return 0;
}
The first f() works, but the second gives a compile time error:
f(vector<Deriv *>) not found.
My question: is there a way to make it work: some kind of polymorphism with vectors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您想要的属性称为协方差。答案是否定的,你不能这样做:向量不是协变的。
为什么不允许这样做的典型示例如下:
如果您不向向量添加元素,则可以仅传递一对输入迭代器。传递输出迭代器也不起作用。
The property you want is called covariance. And the answer is no, you cannot do this: vectors are not covariant.
The canonical example of why this is not allowed goes like this:
If you're not adding elements to the vector, you can just pass a pair of input iterators. Passing output iterators would not work either.
AFAIK 不是您想要的方式(
vector
与vector
是根本不同的类型)。这是一种替代方法 - 这当然是一种通用
算法
AFAIK not the way you would like (
vector<Base*>
is a fundamentally different type tovector<Deriv*>
).Here's one alternative approach - this is of course a general algorithm
To call
您应该在 main 中编写此代码
您仍然可以将
Derived
对象推送到容器中,并且f()
工作正常。模板解决方案也很好:
You should write this in main
You can still push the
Derived
objects into container andf()
works fine.Template solution is good as well:
Base
和Deriv
是协变类型,但std::vector
和std::vector;
不是协变类型。当
X
是协变类型B
的对象时,您可以分配从B
派生的任何类型D
的对象,到X
。这就是你的第一个案例中发生的情况。Base
andDeriv
are covariant types, butstd::vector<Base*>
andstd::vector<Deriv*>
are not covariant types.When
X
is an object of a covariant typeB
, you can assign object of any typeD
derive fromB
, toX
. That is what happens in your first case.