I’m storing an std::map of std::shared_ptr<V> as value.
From one functions, I want to return a reference to this map, but with std::shared_ptr<const V> as value type, is that possible ?
Here is what I want to achieve:
#include <map>
#include <memory>
struct A {
std::map<int, std::shared_ptr<int>> map;
const std::map<int, std::shared_ptr<const int>>& ret1() const {
return map;
}
};
But this code fails to compile:
error: invalid initialization of reference of type
'const std::map<int, std::shared_ptr<const int> >&'
from expression of type 'const std::map<int, std::shared_ptr<int> >'
Thanks
A type
Tand a typeconst Tare related but ultimately different types. If you don’t want the caller ofret1to modify the values in your map, then either return a copy of the map, or accept a reference to a map as argument and copy the keys and values into that.