MSVC:C ++ 14:std:set:比较函数:为什么需要“const”?

2023-12-14

示例代码:

#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?


This is LWG2542。在 C++14 中,比较运算符的措辞是“可能是 const”,GCC 和 Clang 将其解释为意味着比较运算符不需要是const合格的。 MSVC 总是需要它。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MSVC:C ++ 14:std:set:比较函数:为什么需要“const”? 的相关文章

随机推荐