为什么 std::equality_comparable 不适用于 std::vector
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
内部失败,而不是在受概念保护的函数边界处失败。
这是错误还是预期行为?
概念仅检查声明是否格式正确,不检查定义。
std::vector
的 comparison operators 不是 SFINAE 友好的,即它们是无条件声明的,这意味着 operator==(vector<T>, vector<T>)
始终存在,即使 operator==(T, T)
不存在。这就是为什么 equality_comparable<std::vector<T>>
总是满足并且函数内部 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 );
我正在研究概念,并希望 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
内部失败,而不是在受概念保护的函数边界处失败。
这是错误还是预期行为?
概念仅检查声明是否格式正确,不检查定义。
std::vector
的 comparison operators 不是 SFINAE 友好的,即它们是无条件声明的,这意味着 operator==(vector<T>, vector<T>)
始终存在,即使 operator==(T, T)
不存在。这就是为什么 equality_comparable<std::vector<T>>
总是满足并且函数内部 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 );