将vector<shared_ptr<Derived>>传递给一个期望接收vector<shared_ptr<Base>>的函数

5

我遇到了一个与代码结构相关的问题,代码结构如下(简化):

class SPoint
{
public:
    SPoint(double x, double y, double z) : _x(x), _y(y), _z(z) {}

protected:
    double _x, _y, _z;
}

class Point3D : public SPoint
{
public:
    Point3D(double x, double y, double z) : SPoint(x, y, z) { // default values for U and V }

protected:
    double U, V;
}

这些点用于创建折线:

class SPolyline
{
public:
    SPolyline(const vector<shared_ptr<SPoint>>& points) { // points are cloned into _points}

protected:
    vector<shared_ptr<SPoint>> _points;
};


class Polyline3D : SPolyline
{
public :
    Polyline3D(const vector<shared_ptr<Point3D>>& points) : SPolyline(points)  // doesn't compile
};

当我尝试编译Polyline3D时,VS2010拒绝了我的请求,并显示了以下错误信息:

error C2664: 'SPolyline::SPolyline(const std::vector<_Ty> &)' : cannot convert parameter 1 from 'const std::vector<_Ty>' to 'const std::vector<_Ty> &'
with
[
  _Ty=std::tr1::shared_ptr<SPoint>
]
and
[
  _Ty=std::tr1::shared_ptr<Point3D>
]
and
[
  _Ty=std::tr1::shared_ptr<SPoint>
]
Reason: cannot convert from 'const std::vector<_Ty>' to 'const std::vector<_Ty>'
with
[
  _Ty=std::tr1::shared_ptr<Point3D>
]
and
[
  _Ty=std::tr1::shared_ptr<SPoint>
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

vector<shared_ptr<Derived>> 不能默认转换为 vector<shared_ptr<Base>>。 如何解决这个问题,同时确保我需要多条线上的点具有共享所有权?我使用的 shared_ptr 是标准的,而不是来自 Boost 库。

2个回答

5
从容器中抽象出来并使用迭代器。
template<typename InputIterator>
Polyline3D(InputIterator begin, IntputIterator end) : SPolyline(begin ,end) {}

可以实现vector的这种转换,但考虑到它可能引入的微妙错误(比如隐式转换),不实现它可能更好。


SPolyline的构造函数也需要模板化吗? - undu
@undu 当然可以。如果你使用的是C++11,你可以使用继承构造函数。另外:你所有的例子在类声明的末尾都缺少了一个分号 ;) - pmr
非常感谢您的出色回答,它对我的情况非常有效,并且我从中学到了很多!! - undu

0

你可以做的另一件事是:

class Polyline3D : public SPolyline
{
public :
    Polyline3D(const vector<shared_ptr<Point3D>>& points) : SPolyline(std::vector<shared_ptr<SPoint> >(points.begin(), points.end())){}  
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接