是否可用于当前使用默认运算符C
的标准算法?std::sort
<
是的,它适用于std::sort()
其他一些标准算法。编码
#include <algorithm>
#include <vector>
struct C
{
/* Class contents, without any arithmetic operator... */
constexpr operator int() noexcept {return 0;} // Implicit conversion to int
};
int main()
{
std::vector<C> v;
std::sort( begin(v), end(v) );
}
编译。这是一个现场演示。不过看下一个问题!
是否C
被视为满足LessThanComparable
概念?
不。这个LessThanComparable
概念的要求是,对于对象x
和y
类型C
或const C
表达式x<y
是有效的,并且可以隐式转换为 bool,并且<
运算符建立严格的弱排序关系。在您的情况下, const 对象不会转换为int
s。这是您的代码中的一个错误,因为它不是 const 正确的。添加const
关键字将使其工作,并且该类C
确实是LessThanComparable
. 满足严格的弱排序关系,因为int
s 满足这个要求。
将C
满足要求类型为LessThanComparable
.
如果你修复你的 constness,是的,它会的。
一些旁注:
GCC 4.9 编译x<y
即使x
和y
是const C
. 这似乎是一个编译器错误,因为 GCC 5.2 和 clang 3.6 在这里抛出了编译时错误。
std::less<C>()
作为一个额外的参数传递给std::sort()
编译时错误,因为比较函数需要常量对象在这种情况下是可比较的。但是,传递std::less<void>()
不会破坏任何东西,因为参数是完美转发的。
std::sort()
算法不需要完整,LessThanComparable
但需要概念Compare
。此外,迭代器类型必须是 a RandomAccessIterator
that isValueSwappable
并且取消引用的类型必须是MoveContructable
and MoveAssignable
。这就是您的第一个问题的全部情况,即使没有修复 constness 错误。这就是std::sort()
其他标准算法起作用的原因。