Here’s a simple question regarding const correctness.
I have this class:
template <class T>
class Foo
{
public:
std::map<std::string, boost::any> members;
template <typename T>
std::vector<T>& member(const std::string& memberName)
{
return boost::any_cast<std::vector<T>&>(members[memberName]);
}
};
I then have a functor which includes the following:
bool operator()(Foo& foo) const
{
std::vector<T> & member = foo.member<T>(_memberName);
What confuses me here is that I cant pass Foo by reference to const, since I’m calling the non const member getter function. With regard to its signature, this gives the impression that operator() changes foo.
Should I correct this and if so how?
The usual way is to add a
constoverload for the member function:Calling the member on a
const Foowill choose this overload; calling it on a non-constwill choose the original one.
Note that
at()is a fairly new addition tostd::map. If you’re stuck with an outdated library, you’ll need something like: