在下面的示例代码中,重载运算符<没有被const限定,它可以在Visual C++(所有版本都适用到2013 Preview)下编译通过,但是在Clang下,它会抛出一个错误-注意:候选函数不可行:'this'参数具有类型'const Entry',但方法未标记为const bool operator<( const Entry& other )。
Visual C++在强制执行比较/关系运算符的const正确性方面是否不符合标准?或者这与std::sort有关?
#include "stdafx.h"
#include <vector>
#include <algorithm>
struct Entry
{
unsigned int age;
bool operator<( const Entry& other ) // !!! no const qualification here !!!
{
return age < other.age;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<Entry> entries;
for( unsigned int i = 0; i < 100; ++i )
{
Entry entry;
entry.age = i;
entries.push_back( entry );
}
// Sort by age
std::sort( entries.begin(), entries.end() );
return 0;
}
Visual C++在强制执行比较/关系运算符的const正确性方面是否不符合标准?或者这与std::sort有关?
std::sort
实现的问题:clang在const
上下文中比较对象,而VC++则没有。 一般情况下,当clang和VC++意见不一致时,通常是因为VC++的实现存在错误。 :) - Yakk - Adam Nevraumont