c++ - Getter 函数的 Const 正确性

标签 c++

这是一个关于 const 正确性的简单问题。

我有这门课:

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

然后我有一个包含以下内容的仿函数:

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

这里让我感到困惑的是我不能通过引用 const 来传递 Foo,因为我正在调用非 const 成员 getter 函数。关于它的签名,这给人的印象是 operator() 改变了 foo。

我应该更正这个吗?如果是的话,应该如何更正?

最佳答案

通常的方法是为成员函数添加一个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));
}                                         ^^^^^            ^^

const Foo 上调用成员将选择此重载;在非 const 上调用它 会选择原来的。

请注意,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);

关于c++ - Getter 函数的 Const 正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12426215/

相关文章:

c++ - 将 unique_ptr 分配给第一个内的另一个 unique_ptr 是否安全?

c++ - OpenCV:基于三角选择倾斜图像

c++ - __declspec(restrict) 和 __declspec(noalias) 有什么区别

c++ - 来自头文件/源文件的包含文件

c++ - 我可以告诉对象删除我吗?

c++ - 如何解决由于参数中的默认构造函数导致的函数重载不明确

c++ - 将字符串转换为整数数组

c++ - 编译程序 linux 32 位 vs 64 位

c++ - 来自 boost::multi_array 的二维数组 - 无法编译

c++ - 自定义结构错误 : "VS 2015 error C2678: binary ' <': no operator found which takes a left-hand operand of type ' const Node'"