c++ - MSVC : C++14: std:set: comparison function: why "const" is required?

标签 c++ visual-c++ c++14 const-correctness stdset

示例代码:

#include <string>
#include <set>

using namespace std;

class x
{
private:
  int i;
public:
  int get_i() const { return i; }
};

struct x_cmp
{
    bool operator()(x const & m1, x const & m2)
#if _MSC_VER
    const
#endif
    {
        return m1.get_i() > m2.get_i();
    }
};

std::set<x, x_cmp> members;

void add_member(x const & member)
{
    members.insert(member);
}

调用:

$ g++ -c -std=c++14 -pedantic -Wall -Wextra
<nothing>
$ clang++ -c -std=c++14 -pedantic -Wall -Wextra
<nothing>
$ icc -c -std=c++14 -pedantic -Wall -Wextra
<nothing>
$ cl /c /std:c++14 /Za
<nothing>

问题:为什么 msvc 需要 const 而其他人不需要?或者为什么其他人不需要 const

最佳答案

这是LWG2542 .在 C++14 中,比较运算符的措辞是“可能是 const”,GCC 和 Clang 将其解释为表示比较运算符不需要是 const 限定的。 MSVC 总是需要它。

这是一个措辞缺陷,因为关联容器的比较运算符应该是 const 限定的。这在 C++17 中已更改为要求比较器为 const。这是一个重大更改,因此有效(尽管已损坏)的 C++14 代码可能无法在 C++17 中编译。

关于c++ - MSVC : C++14: std:set: comparison function: why "const" is required?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70975761/

相关文章:

c++ - 基于运算符推导模板返回类型? : result

c++ - 将链接切割树的 C++ 实现转换为 C

c++ - SFML 2.0 中需要的警告框功能

c++ - C++14 及更高版本是否允许 Lambda 函数的默认参数?如果是这样怎么办?

c++ - MFC中如何对CListCtrl中的Item进行排序?

C++ 智能感知 : expression must be a modifiable lvalue

c++ - 在 C++14 中,constexpr 成员可以更改数据成员吗?

c++ - 从 sizeof 自动扣除的类型在 Visual Studio C++ 和 GCC 之间不同

c++ - SetThreadAffinityMask() 似乎不止一次生效

c++ - Qt 更新单个 XML 元素