2012-09-14 32 views
5

下面是關於const正確性的一個簡單問題。吸氣功能的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]); 
    } 
}; 

然後我有一個仿函數,其中包括以下內容:

​​

什麼這裏讓我困惑的是,我不能按引用傳遞美孚爲const,因爲我調用非const成員getter函數。關於它的簽名,這給人的印象是operator()改變foo。

我應該改正這一點,如果是的話如何?

回答

9

通常的方法是添加一個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); 
2

const正確性適用於您執行其方法的對象。所以:

bool operator()(Foo& foo) const 

意味着operator()不會改變在函數子類東西,像_memberName(這似乎是仿函數類的成員)。

它被定義的方式允許更改Foo(調用非const方法)。

編輯: ,因爲它描述了一個方法來解決它的見Mike Seymour答案。我個人已經做了很多,但似乎並沒有得到你的問題。 :)

+0

但問題是,我們可以安排通過'const'參考傳遞'foo'嗎? –