简体   繁体   中英

Const Correctness for Getter Function

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 const overload for the 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 the member on a const Foo will choose this overload; calling it on a non- const will choose the original one.

Note that at() is a fairly new addition to std::map . If you're stuck with an outdated library, you'll need something like:

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);

The const correctness applies on the object, whose method you execute. So:

bool operator()(Foo& foo) const

means that operator() will not change anything in the functor class, like the _memberName (which seems to be a member of the functor class).

The way it is defined, it is allowed to change Foo (call non-const methods).

EDIT : See Mike Seymour 's answer as it describes a way to fix it. I personally have done that a lot but didn't seem to get exactly your question. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM