简体   繁体   English

Getter函数的Const正确性

[英]Const Correctness for Getter Function

Here's a simple question regarding const correctness. 这是一个关于const正确性的简单问题。

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. 让我困惑的是,我不能通过引用传递给Foo,因为我正在调用非const成员的getter函数。 With regard to its signature, this gives the impression that operator() changes foo. 关于它的签名,这给人的印象是operator()改变了foo。

Should I correct this and if so how? 我应该纠正这个,如果是这样的话?

The usual way is to add a const overload for the member function: 通常的方法是为成员函数添加一个const重载:

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; const Foo上调用成员将选择此重载; calling it on a non- const will choose the original one. 在非const上调用它将选择原始的。

Note that at() is a fairly new addition to std::map . 请注意at()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. const正确性适用于您执行其方法的对象。 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). 表示operator()不会更改_memberName函数类中的任何内容,例如_memberName (它似乎是_memberName函数类的成员)。

The way it is defined, it is allowed to change Foo (call non-const methods). 它的定义方式,允许改变Foo(调用非const方法)。

EDIT : See Mike Seymour 's answer as it describes a way to fix it. 编辑 :请参阅Mike Seymour的回答,因为它描述了修复它的方法。 I personally have done that a lot but didn't seem to get exactly your question. 我个人已经做了很多,但似乎没有得到你的问题。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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