2012-07-20 98 views
4

我面臨的一個問題與代碼結構我使用,這是如下(簡化):傳遞矢量<shared_ptr的<Derived>>到功能期待矢量<shared_ptr的<Base>>

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

VS2010拒絕我,當我嘗試編譯Polyline3D與此錯誤

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。

回答

5

摘要遠離你的容器並使用迭代器。

template<typename InputIterator> 
Polyline3D(InputIterator begin, IntputIterator end) : SPolyline(begin ,end) {} 

有可能實現這樣的轉換爲vector,但沒有給它微妙的事故,它可以引入(想想內隱的轉換)可能是更好的。

+0

SPolyline構造也應該被模板? – undu 2012-07-20 15:40:51

+0

@undu當然可以。如果您使用C++ 11,則可以使用繼承構造函數。另外:你所有的例子都在類聲明結尾缺少一個分號;) – pmr 2012-07-20 15:46:36

+0

非常感謝這個偉大的答案,它對我的​​案例非常有用,並且我從中學到了很多! – undu 2012-07-24 14:13:17

0

你可以做的另一件事是:

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