[英]Const Correctness for Getter Function
這是一個關於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);
讓我困惑的是,我不能通過引用傳遞給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);
const正確性適用於您執行其方法的對象。 所以:
bool operator()(Foo& foo) const
表示operator()
不會更改_memberName
函數類中的任何內容,例如_memberName
(它似乎是_memberName
函數類的成員)。
它的定義方式,允許改變Foo(調用非const方法)。
編輯 :請參閱Mike Seymour的回答,因為它描述了修復它的方法。 我個人已經做了很多,但似乎沒有得到你的問題。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.