Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 607
TripShock Avatar asked May 17 '11 01:05

TripShock


1 Answers

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.

like image 91
Mark B Avatar answered Sep 28 '22 20:09

Mark B