开发者

Safely convert (vector of shared_ptr to objects) to (vector of shared_ptr to constant objects)

class A {};

typedef shared_ptr<const A*> AConstPtr;
typedef shared_ptr<A*> APtr;

vector<APtr> ptr;

const vector<AConstPtr>* foo()
{
    return &ptr;
}

This code does not compile, because "there is no implicit conversion from vector<Aptr>* to const vector<AConstPtr> * " Is there anyway to make this work, without creating a new vector, and without using an unsafe开发者_StackOverflow中文版 cast?

The reason why I need this is because I have a class that stores a list internally as vector<APtr>, but needs to expose a completely const version of it through its interface.


There's no way to do such a conversion since different shared_ptrs aren't related types.

First, are you really sure that you need to expose the implementation detail that there's an internal vector of shared pointers? That's really going to tie you to that implementation and it won't be subject to change without breaking API.

What about using @Cubbi's suggestion and having your interface be interators with begin and end methods instead? Then you can easily represent a container to the outside clients without tying yourself to vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜