【问题标题】:C++ nested map no matching member function const memberC++ 嵌套映射没有匹配的成员函数 const 成员
【发布时间】:2016-10-01 21:28:54
【问题描述】:

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

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

【问题讨论】:

  • 它应该可以工作并且works for me。也许将您的代码+错误粘贴到问题中。
  • 你是在问搜索的调用吗?
  • 给我一些时间来减少问题,无法粘贴确切的代码。
  • @AnuragPeshne 你或许应该在发布之前投入这段时间!

标签: c++ stl stdmap


【解决方案1】:

将内部映射的键声明为指向const 对象的指针。否则,当您在 const 函数中传递 this 时,您传递的是 Foo&lt;T&gt; const* 而不是 Foo&lt;T&gt;*,并且您无法隐式转换。

所以

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 - 已修复。

【讨论】:

  • 哦,所以这是关于 this 而不是嵌套地图。当函数声明 const 时,this 变为 const 指针。谢谢,成功了。
猜你喜欢
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
相关资源
最近更新 更多