简体   繁体   English

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

[英]C++ nested map no matching member function const member

I have a nested map, something like我有一个嵌套的地图,比如

map = {
  key : {
    innerKey: innerVal
  }
}

I'm trying to search for innerVal from member function marked as const .我正在尝试从标记为const成员函数中搜索innerVal I'm using at() as described here C++ map access discards qualifiers (const) which gets me to map pointed by key .我正在使用at() ,如此处所述C++ 映射访问丢弃限定符 (const) ,它使我能够映射由key指向的映射。 But, when I try to use at() on nested map, I get an error:但是,当我尝试在嵌套地图上使用at()时,出现错误:

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

Workaround: I can use a iterator and linearly search on the nested map, which works perfectly.解决方法:我可以使用迭代器并在嵌套地图上线性搜索,这非常有效。 How can I use functions such as at() or find() to search in nested map.如何使用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

}

Edit: it works for above simplified code, try this , and try removing const keyword from line 20.编辑:它适用于上述简化代码,试试这个,并尝试从第 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());
}

Declare your inner map's key to be a pointer to const object.将内部映射的键声明为指向const对象的指针。 Otherwise when you pass this in a const function you pass Foo<T> const* instead of Foo<T>* and you can't convert that implicitly.否则,当您在 const 函数中传递this时,您将传递Foo<T> const*而不是Foo<T>*并且您无法隐式转换它。

So所以

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

to

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

And the same in the definition.和定义相同。

live example of your example - fixed.你的例子的活生生的例子 - 固定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM