C++嵌套映射没有匹配的成员函数常量成员

C++ nested map no matching member function const member

我有一个嵌套地图,类似于

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 行删除 const 关键字。

#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());
}

将内部地图的键声明为指向 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 您的示例 - 已修复。