2016-10-01 105 views
-1

我有一個嵌套的地圖,像C++嵌套地圖沒有匹配的成員函數const成員

map = { 
    key : { 
    innerKey: innerVal 
    } 
} 

我試圖從標記爲const成員函數搜索innerVal。我正在使用at(),這裏描述C++ map access discards qualifiers (const) 它讓我去key指出的地圖。但是,當我嘗試嵌套的地圖上使用at(),我得到一個錯誤:

error: no matching member function for call to 'at' 

解決方法:我可以用一個迭代器和嵌套映射,它完美的作品上線搜索。如何使用at()find()等功能在嵌套地圖中進行搜索。

TLDR:

private std::map<int, std::map<int, int> > privateStore; 

int search(int key1, int key2) const { 
    return privateStore.at(key1).at(key2); //works when I remove `const` from function signature 

} 

編輯:它適用於上述簡化代碼,try this,並試圖從線20

#include <iostream> 
#include <map> 
#include <thread> 

template <typename T> 
class Foo 
{ 
public: 
    Foo() 
    { 
    std::cout << "init"; 
    } 

    void set(T val) 
    { 
    privateStore[std::this_thread::get_id()][this] = val; 
    } 

    T search(std::thread::id key1) const 
    { 
    std::map<Foo<T>*, T> retVal = privateStore.at(key1); //works when I remove `const` from function signature 
    return retVal.at(this); 
    } 

private: 
    static std::map<std::thread::id, std::map<Foo<T>*, T> > privateStore; 
}; 

template<typename T> std::map<std::thread::id, std::map<Foo<T>*, T> > Foo<T>::privateStore = {}; 

int main() 
{ 
    Foo<int> a; 
    a.set(12); 
    std::cout << a.search(std::this_thread::get_id()); 
} 
+0

它應該工作[適用於我](http://melpon.org/wandbox/permlink/cAVXxUYOKBVoYmjX)。也許將你的代碼+錯誤粘貼到問題中。 – krzaq

+0

[對我也適用](http://cpp.sh/2lelj) – CoryKramer

+0

您是否在詢問關於搜索的調用? –

回答

1

去除const關鍵字聲明你的內心地圖的關鍵是指向const對象。否則,當您在const函數中傳遞this時,您將傳遞Foo<T> const*而不是Foo<T>*,並且無法隱式轉換。

所以

static std::map<std::thread::id, std::map<Foo<T> *, T> > privateStore; 

static std::map<std::thread::id, std::map<Foo<T> const*, T> > privateStore; 

而且在定義是相同的。

live example你的例子 - 修復。

+0

哦,所以這是關於'this'而不是嵌套地圖。函數聲明爲'const'時,'this'變成const指針。謝謝,它工作。 –