According to this page you can implicitly convert shared_ptr<Foo> to shared_ptr<const Foo>. That makes good sense.
However, I run into an error when I try to convert a std::vector containing shared_ptr<Foo> to one containing shared_ptr<const Foo>.
Is there a good way to achieve this conversion?
No:
std::vector<shared_ptr<Foo> >andstd::vector<shared_ptr<const Foo> >are different types, so you can’t treat an object of one as an object of the other type.If you really need a
std::vector<shared_ptr<const Foo> >, you can easily create one withshared_ptrs to the same elements as the original:However, if you write your code in terms of iterators, you shouldn’t have any problem with this. That is, instead of using
you should be using
This way, the function
fjust requires that it gets a range of things that are usable as pointers toconst Foo(orshared_ptr<const Foo>s, if the function assumes that the range containsshared_ptrs).When a function takes a range instead of a container, you decouple the function from the underlying data: it no longer matters what the data actually is or how it is stored, so long as you can use it in the way that you need to use it.