Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason why in C++20 std::vector operator == does not work for vectors with different allocators?

Note:

I know usual reasons are possible: nobody thought of it/wrote paper/WG21 did not think it is worth the effort, I am more interested in technical problems that prevent potential implementation than in the value of utility of this functionality.

I always found it weird that this does not work(even before concepts, since we could use enable_if)

#include <vector>
#include  <boost/align/aligned_allocator.hpp>
int main()
{
    std::vector<int> a{1,2,3};
    std::vector<int, boost::alignment::aligned_allocator<int,64>> b{1,2,3};
    return a==b;
}

Reason is that allocators do not affect the values stored in the container(I understand that values could be using their address in the operator ==, I am talking about "normal" types).

So my question is: if we wanted to do it with C++20 concepts could we introduce this functionality without breaking any existing code?

like image 478
NoSenseEtAl Avatar asked Jan 25 '23 05:01

NoSenseEtAl


1 Answers

There aren't any technical problems. It's certainly trivial to implement:

template <std::equality_comparable T, typename A1, typename A2>
bool operator==(std::vector<T, A1> const& lhs, std::vector<T, A2> const& rhs) {
    return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}

And then why stop at allocators? Why can't I compare a vector<int> to a vector<long>?

P0805 is the proposal for widening the comparison set to allow comparing both mixed-type and mixed-allocator containers. It was approved for C++20, but didn't make the cut and still needs some work to fit in with the new C++20 concepts (notably, equality_comparable_with requires common_reference: what's the common reference between two vectors having different allocators?)


In the meantime, std::ranges::equal(v1, v2) works for heterogeneous vectors.

like image 134
Barry Avatar answered Jan 30 '23 02:01

Barry