Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::equality_comparable not work for std::vector

https://godbolt.org/z/P97MaK

I'm playing with concepts and expected std::is_equality_comparable to work for vector but it does not.

#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>{});
    
}

the compile error fails inside foo rather than at the function boundary protected by the concept.

enter image description here

Is this a bug or expected behaviour?

like image 690
bradgonesurfing Avatar asked Oct 16 '25 23:10

bradgonesurfing


1 Answers

A concepts only checks that the declaration is well formed, it doesn't check the definition.

The comparison operators for std::vector are not SFINAE friendly, i.e. they are unconditionally declared, meaning that operator==(vector<T>, vector<T>) always exists, even if operator==(T, T) doesn't exists. That's why equality_comparable<std::vector<T>> is always satisfied and you get an error on v == v inside the function.

For it to work properly the vector comparison operators should be constrained, i.e.:

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 );
like image 166
bolov Avatar answered Oct 18 '25 14:10

bolov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!