我了解this question的内容,但是当使用函数重载时,事情如何工作?
例如,在std::map
中,定义了以下方法:
iterator find (const key_type& k);
const_iterator find (const key_type& k) const;
如何使用
auto
关键字选择一个或另一个?以下内容对我来说似乎不正确:auto i = mymap.find(key); //calls the non-const method?
const auto i = mymap.find(key); //calls the const method?
最佳答案
std::map<int, int> mutable_map;
const std::map<int, int> const_map;
mutable_map.find(1); // returns iterator
const_map.find(1); // returns const_iterator
您不希望从常量
map
返回常规迭代器,因为这会破坏常量性。因此,拥有一个与常量find
明智地工作的map
成员函数的唯一方法是使const
重载返回const_iterator
。