Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implicit conversion from std::vector<std::shared_ptr<T>> to std::vector<std::shared_ptr<const T>>

I have a function requiring const std::vector<std::shared_ptr<const T>>& as signature. It seems that compiler doesn’t allow me to pass in a std::vector<std::shared_ptr<T>>. Wondering why it cannot implicitly convert from std::vector<std::shared_ptr<T>> to std::vector<std::shared_ptr<const T>>.

I tried passing an object of std::vector<std::shared_ptr<T>> to a function requiring const std::vector<std::shared_ptr<const T>>& as signature. It fails to compile.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since there is no implicit conversion between std::vectors with different template arguments. Just write helper function:


Marek R

class Foo {};

std::vector<std::shared_ptr<const Foo>> convert(const std::vector<std::shared_ptr<Foo>>& v)
{
    return {v.begin(), v.end()};
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading