[英]Why does std::equality_comparable not work for std::vector
我正在玩概念,并期望 std::is_equality_comparable 可以为向量工作,但事实并非如此。
#include <type_traits>
#include <vector>
#include <concepts>
struct X {};
template<std::equality_comparable T>
bool foo( T v){
return v == v;
}
int main()
{
foo(10);
foo(std::vector<X>{});
}
编译错误在foo
内部而不是在受概念保护的 function 边界处失败。
这是错误还是预期行为?
概念仅检查声明是否格式正确,不检查定义。
std::vector
的比较运算符不是 SFINAE 友好的,即它们是无条件声明的,这意味着operator==(vector<T>, vector<T>)
始终存在,即使operator==(T, T)
不存在'存在。 这就是为什么总是满足equal_comparable equality_comparable<std::vector<T>>
并且在function 中的v == v
上出现错误的原因。
为了使其正常工作,应该限制向量比较运算符,即:
template< class T, class Alloc >
requires std::equality_comparable<T>
constexpr ret_type operator==( const std::vector<T,Alloc>& lhs,
const std::vector<T,Alloc>& rhs );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.