将vector <shared_ptr <Derived >>传递给期望向量<shared_ptr <Base >>的函数

und*_*ndu 4 c++ inheritance smart-pointers shared-ptr

我正在使用我使用的代码结构的问题,如下(简化):

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;
}
Run Code Online (Sandbox Code Playgroud)

这些点用于创建折线:

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
};
Run Code Online (Sandbox Code Playgroud)

当我尝试使用此错误编译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
Run Code Online (Sandbox Code Playgroud)

没有默认转换vector<shared_ptr<Derived>>vector<shared_ptr<Base>>.知道我需要折线中点的共享所有权,如何解决这个问题?在shared_ptr我使用的是标准的,而不是从升压.

pmr*_*pmr 5

摘要远离容器并使用迭代器.

template<typename InputIterator>
Polyline3D(InputIterator begin, IntputIterator end) : SPolyline(begin ,end) {}
Run Code Online (Sandbox Code Playgroud)

有可能实现这样的转换vector,但考虑到它可以引入的微妙意外(认为隐含的转换)不会让它更好.