Vin*_*ent 16 c++ implicit-conversion stl-algorithm c++-concepts c++17
考虑以下课程:
struct C
{
/* Class contents, without any arithmetic operator... */
constexpr operator int() noexcept; // Implicit conversion to int
};
Run Code Online (Sandbox Code Playgroud)
我的问题是:
std::sort当前使用默认<运算符的标准算法?LessThanComparable概念吗?LessThanComparable.Ral*_*zky 12
是
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) );
}
Run Code Online (Sandbox Code Playgroud)
编译.这是一个现场演示.看看下一个问题吧!
被
C认为是令人满意的LessThanComparable概念?
否.LessThanComparable概念的要求是,对于对象x和y类型C或const C表达式x<y是有效的并且可以隐式地转换为bool,并且<运算符建立严格的弱有序关系.在你的情况下,const对象不会转换为ints.这是代码中的错误,因为它不是const正确的.添加const关键字将使其工作,而类C确实会LessThanComparable.严格的弱有序关系得以实现,因为ints满足了这一要求.
将
C满足需要类型的假设的概念算法库的要求LessThanComparable.
如果你修复你的常数,是的,它会.
一些旁注:
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.此外,迭代器类型必须是RandomAccessIterator,ValueSwappable并且取消引用类型必须是MoveContructable和MoveAssignable.对于第一个问题,这就是所有情况,即使constness bug没有修复.这就是原因std::sort()和其他标准算法的工作原理.
| 归档时间: |
|
| 查看次数: |
599 次 |
| 最近记录: |