Avoiding unnecessary comparison operators in C++20

success strategy business solution 2081167
25 de enero de 2023

One advantage of the new c++20 standard is the possibility to program more with less code. This follows the principle of Don't Repeat Yourself (aka DRY), which aims to avoid unnecesary code which makes our software more difficult -and therefore expensive- to maintain.

A good example is when we need to compare two types and check if they are equals or not.

In many software proyects, we and up with different types representing the same concept but implemented differently in different libraries.

Let's consider the following example: A struct representing a singe point with two coordinates:

struct Point {
  int x;
  int y;
};

This is a common type in many libraries, so imagine we make use of a NewPoint struct in another place that represent the same concept:

struct NewPoint {
  int a;
  int b;
};

At some point we need to check if two points are in fact the same. The compailer will complain if we use the operator == with objects of different types, so we need to write our own comparison:

struct NewPoint {
  int a;
  int b;

  constexpr bool operator==(const Point& rpoint) const noexcept
  {
      return (a == rpoint.x) && (b == rpoint.y);
  }
};

This allows to compare a newPoint with a Point, but not the other way around. That is:

 Point p = {2,4};
 NewPoint nP = {2,4};
 auto same = nP == p ? "yes" : "no";
 std::cout << same  << "\n";

This code compiles and return yes, but we're comparing a NewPoint with a Point, which means, if we write the comparison in this way:

 auto same = p == nP ? "yes" : "no";

It won't compile in C++17. We need to impement the operator== in Point as well, which would be 95% identical to the previous one.

However, in C++20 the compiler understand the mathematical sense of the identity and is able to invoke the operator== of NewPoint, event though p is of type Point!

This means that we don't have to implement a dedicated operator== in Point, as the compiler knows that if nP== p, then p == nP !

This avoids the need of a dedicated operator== in Point and follows the DRY principle.


Compártelo en Facebook Twitter LinkedIn e-mail

    CONTACTA CON NOSOTROS



    Responsable: Blau Ring Labs SL. Finalidad: Recibir y responder a la consulta actual y posibles comunicaciones comerciales derivadas de la misma. Legitimación: Su autorización expresa al marcar la casilla correspondiente en este formulario. Destinatarios: Solo el personal de la empresa responsable tendrá acceso a los datos. Los datos no serán cedidos a terceras empresas con fines comerciales. Derechos: Tiene derecho a conocer qué datos guardamos sobre usted, a rectificarlos y a eliminarlos tal y como se explica en nuestra política de privacidad.