简体   繁体   English

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

[英]MSVC: C++14: std:set: comparison function: why "const" is required?

Sample code:示例代码:

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

Invocations:调用:

$ 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>

Question: why msvc requires const while others don't?问题:为什么 msvc 需要const而其他人不需要? Or why others don't require const ?或者为什么其他人不需要const

This is LWG2542 .这是LWG2542 In C++14, the wording for the comparison operator said "possibly const", which was interpreted by GCC and Clang as meaning that the comparison operator was not required to be const qualified.在 C++14 中,比较运算符的写法是“可能是 const”,GCC 和 Clang 将其解释为不需要const的意思。 MSVC always required it. MSVC 总是需要它。

This is a wording defect, as comparison operators for associative containers should be const qualified.这是一个措辞缺陷,因为关联容器的比较运算符应该是const限定的。 This was changed in C++17 to require the comparator to be const .这在 C++17 中进行了更改,要求比较器为const This is a breaking change, so valid (though broken) C++14 code may fail to compile in C++17.这是一个重大更改,因此有效(尽管已损坏)C++14 代码可能无法在 C++17 中编译。

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

相关问题 为什么C ++ 14中没有std :: allocate_unique函数? - Why is there no std::allocate_unique function in C++14? C ++ 14 constexpr静态const std :: array初始化 - C++14 constexpr static const std::array initialization 如果在C ++ 14或更高版本上,非const的成员函数应该只是constexpr - member function that is not const should only be constexpr if on C++14 or later 为什么 `constexpr` 是`std::max()` 的 C++14 模板原型的一部分? - Why is `constexpr` part of the C++14 template prototype for `std::max()`? 为什么在 C++14 中使用 std::bind 而不是 lambdas? - Why use std::bind over lambdas in C++14? 为什么std :: tie没有标记为c ++ 14的constexpr? - Why is std::tie not marked constexpr for C++14? 为什么在 C++14 中不推荐使用 std::shuffle 方法? - Why are std::shuffle methods being deprecated in C++14? C++14:具有泛型 std::function 作为类成员的泛型 lambda - C++14: Generic lambda with generic std::function as class member 来自&#39;const std :: vector的无效转换 <cv::Mat> *&#39;到&#39;std :: vector <cv::Mat> *&#39;在c ++ 14中 - Invalid conversion from ‘const std::vector<cv::Mat>*’ to ‘std::vector<cv::Mat>*’ in c++14 在C ++ 14中,const迭代器是否仍然是邪恶的 - Are const iterators still evil in C++14
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM