Const Correctness for Getter Function

Here is 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]);
    }
};

Then I have a functor that includes the following:

bool operator()(Foo& foo) const
{
    std::vector<T> & member = foo.member<T>(_memberName);

What bothers me is that I cannot pass Foo a reference to const, since I call the getter non-member function. As for his signature, it seems that the operator () changes foo.

Should I fix this, and if so, how?

+5
source share
2 answers

The usual way is to add overload constfor a member function:

template <typename T>
std::vector<T> const & member(const std::string& memberName) const
{              ^^^^^                                         ^^^^^
    return boost::any_cast<std::vector<T> const &>(members.at(memberName));
}                                         ^^^^^            ^^

Calling a member on const Foowill select this overload; calling it non-t20> selects the original.

, at() std::map. , - :

std::map<std::string, boost::any>::const_iterator found = members.find(memberName);
if (found == members.end()) {
    throw std::runtime_error("Couldn't find " + memberName);
}
return boost::any_cast<std::vector<T> const &>(found->second);
+9

, . :

bool operator()(Foo& foo) const

, operator() , _memberName (, , ).

, Foo ( ).

: . , . , , , .:)

+2

All Articles