【问题标题】:Passing const object reference to functor将 const 对象引用传递给仿函数
【发布时间】:2017-05-09 23:22:27
【问题描述】:

我想创建一个输入事件对象到 std::functions 的映射。输入事件对象定义了 == 运算符,但由于 map 默认使用

#include <map>

struct Vertex
{
    int x;
    int y;

    constexpr bool operator==(const Vertex& v)
    {
        return (x == v.x) && (y == v.y);
    }
};

struct vertexCmp
{
    bool operator()(const Vertex& v1, const Vertex& v2)
    {
        return v1 == v2;
    }
};

int main()
{
    std::map<Vertex, int, vertexCmp> _vertexMap;

    Vertex v;
    v.x = 1;
    v.y = 1;

    _vertexMap[v] = 1;

    return 0;
}

但是,我收到以下编译器错误:

main.cpp||In member function ‘bool vertexCmp::operator()(const Vertex&, const Vertex&)’:|
main.cpp|21|error: passing ‘const Vertex’ as ‘this’ argument discards qualifiers [-fpermissive]|
main.cpp|11|note:   in call to ‘constexpr bool Vertex::operator==(const Vertex&)’|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

我知道你不能在 const 对象上调用非 const 成员函数,但你会认为 constexpr 会满足这个要求,对吧?我觉得我在这里过度思考了我的方法,并且有更好的方法来构建它。

【问题讨论】:

  • constexpr 和 const 是不同类型的“恒定性”。 constexpr 用于在编译时可能是常量的表达式。 const 不允许在运行时修改值。只需将const 添加到您的operator==
  • 如果你不需要排序也没关系。 std::map 需要排序才能正常工作。它不能通过平等比较来做到这一点。如果你做一个哈希函数,你可以使用std::unordered_map。
  • 我实际上非常喜欢使用散列函数和 unordered_map 的想法,我认为这是一种更好的方法。谢谢。

标签: c++ c++14


【解决方案1】:

在 C++11 中,非静态成员函数上的 constexpr 隐含了 const 函数,但在 C++14 中却没有(因为发现实际上存在 @987654323 函数的用例@ 其中*this 不是const)。你需要

constexpr bool operator==(const Vertex& v) const

【讨论】:

  • 你能给出那个发现的链接吗?会让你的答案完美;)
  • 虽然我将实施 Benjamin Lindley 的建议而不是我原来的方法,但感谢您回答问题。不过,我确实有一个跟进,当在非 const 对象上使用它时,使运算符常量会导致问题吗?
猜你喜欢
  • 1970-01-01
  • 2012-02-25
  • 2016-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
相关资源
最近更新 更多