2016-10-01 11 views
-1

私は、ネストされたマップ、私はconstとしてマークされたメンバ関数からinnerValを検索しようとしているC++ネストされたマップマッチングなしメンバ関数のconstメンバー

map = { 
    key : { 
    innerKey: innerVal 
    } 
} 

のようなものを持っています。私はkeyが指すマップに私を得るのC++ map access discards qualifiers (const) ここに記載されているようにat()を使用しています。私は、ネストされた地図上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オブジェクトです。そうでない場合は、thisをconst関数に渡したときにFoo<T>*の代わりにFoo<T> const*を渡し、それを暗黙的に変換することはできません。

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

と定義同じに

ので

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

live exampleあなたの例は固定です。

+0

ohを参照してください。だから、これはネストされたマップではなく、「これ」に関するものでした。 'this'は関数が' const'を宣言したときにconstポインタになります。ありがとう、それは働いた。 –

関連する問題