C++ Logo

std-discussion

Advanced search

Re: equality compare reference_wrapper

From: Bo Persson <bo_at_[hidden]>
Date: Fri, 26 Mar 2021 07:12:03 +0100
On 2021-03-26 at 02:31, Bernard via Std-Discussion wrote:
> // Microsoft Preview - Features from the Latest C++ Working Draft
> (/std:c++latest)
> // I am trying to equality compare two reference_wrapper objects. The
> compiler generates an error if the contained type is a class so I wrote
> an override. However as you can see below the compiler still generates
> an error. Kindly advise Thank You
>
> #include <functional>
>
> using namespace std;
>
> class cfoobar {
> public: bool operator == (const cfoobar& rhs) const { return true; };
> };
>
> template<typename valueType>
> bool operator == (const reference_wrapper<valueType>& lhs, const
> reference_wrapper<valueType>& rhs) { return lhs.get == rhs.get; }
>
> int main()
> {
> int i = 0;
> int j = 0;
> reference_wrapper<int> rwi = i;
> reference_wrapper<int> rwj = j;
> // line below compiles w/o error
> rwi == rwj;
>
> cfoobar a;
> cfoobar b;
> reference_wrapper<cfoobar> rwa = a;
> reference_wrapper<cfoobar> rwb = b;
> // line below compiles w/ error as shown
> // error C2676 : binary '==' : 'std::reference_wrapper<cfoobar>' does
> not define this operator or
> // a conversion to a type acceptable to the predefined operator
> rwa == rwb;
> }
>

One problem is that get is a function, so you need to call it with get().

    return lhs.get() == rhs.get();



On the other hand, it is not clear that you are allowed to add operators
for standard types. Usually the requirement is that at least one
parameter is of a user-defined type.

Received on 2021-03-26 01:12:14