简体   繁体   English

传递派生对象的智能指针矢量-最佳解决方案是什么?

[英]Passing a vector of smart pointers of derived objects - what is the best solution?

I'm using boost smart pointers of two classes 我正在使用两个类的boost智能指针

class Foo{
};

class Derived : public Foo{
};

typedef boost::shared_ptr<Foo> FooPtr;
typedef boost::shared_ptr<Derived> DerivedPtr;

And I keep a vector of my objects as 我将对象的向量保持为

std::vector<DerivedPtr> myVec;

which I want to use in a method requesting a vector of the base class smart pointers. 我想在请求基类智能指针向量的方法中使用。

Method( std::vector<FooPtr> input ){
... }

Using the vector directly, gives an error on compiling. 直接使用向量会导致编译错误。

cannot convert argument 1 from 'std::vector<DerivedPtr,std::allocator<_Ty>>' to 'std::vector<FooPtr, std::allocator<_Ty>>'

So my current solution is to first 'down-cast' my vector into a new vector of the base class pointers before passing it on: 所以我目前的解决方案是先将向量“下播”到基类指针的新向量中,然后再传递给它:

std::vector<FooPtr> downCastVec;
for ( auto & iter : myVec )
    downCastVec.push_back( iter );

Method( downCastVec );

This works, but my actual question is: 这可行,但是我的实际问题是:

Is there a better/more elegant way to deal with this problem? 有没有更好/更优雅的方式来解决此问题?

Simply use the std::vector constructor overload that takes two iterators, to construct a temporary: 只需使用带有两个迭代器的std::vector构造函数重载来构造一个临时的:

 Method( {myVec.begin(), myVec.end()} )

You can also declare an overload of Method() that takes the vector of derived pointers, for convenience, and just does this. 为了方便起见,您也可以声明Method()的重载,该重载采用派生指针的向量,并做到这一点。 This will prevent some code bloat when this is done frequently. 这样可以防止某些频繁执行的代码膨胀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM