In the 关于概念 N3701 的最新论文 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3701.pdf,有以下示例sort
算法:
template<typename Cont>
requires Sortable<Cont>()
void sort(Cont& cont)
where Sortable
概念定义为
template<typename T>
concept bool Sortable()
{
return Permutable_container<T>() && Totally_ordered<Value_type<T>>();
}
where Totally_ordered
毫不奇怪,被定义为
template<typename T>
constexpr bool Totally_ordered()
{
return Weakly_ordered<T>() && Equality_comparable<T>();
}
反过来Equality_comparable
定义为
template<typename T>
constexpr bool Equality_comparable()
{
return requires(T a, T b) {
{a == b} -> bool;
{a != b} -> bool;
};
}
我没有找到它的定义Weakly_ordered
,但我相信它应该看起来像这样(我对吗?)
template<typename T>
constexpr bool Weakly_ordered()
{
return requires(T a, T b) {
{a < b} -> bool;
{a <= b} -> bool;
{a > b} -> bool;
{a >= b} -> bool;
};
}
底线,在这个定义中,如果我想排序std::vector<T>
,我需要T提供all比较运算符<
, <=
, >
, >=
, ==
, !=
。然而,在 C++ 的整个生命周期中,std::sort
仅需要操作员<
即将呈现!这是什么参考参数 http://en.cppreference.com/w/cpp/algorithm/sort说关于std::sort
:
按升序对 [first, last) 范围内的元素进行排序。这
不保证保留相等元素的顺序。首先
版本使用运算符,第二个版本
使用给定的比较函数对象 comp。
那又怎样,这是否意味着在未来带有概念的 C++ 中,对于v
类型的std::vector<T>
where T
仅提供operator<
, std::sort(v.begin(), v.end())
将编译,同时std::sort(v)
将不会?这听起来很疯狂。
我在当前检查了这个范围-v3 实施 https://github.com/ericniebler/range-v3由埃里克·尼伯勒(Eric Niebler)撰写,它的工作原理就像我所描述的那样。除非提供所有运算符,否则代码不会编译。
另请参阅相关讨论:https://github.com/ericniebler/range-v3/issues/271 https://github.com/ericniebler/range-v3/issues/271