Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two generic types in C++?

Tags:

c++

templates

I need to determine whether an element is the same as the one I'm passing by reference. In the function Belongs I need to compare equality between d is and an element of a stored in a dynamic list:

struct Nodo{ Dominio dominio; Rando rango; Nodo* next; }; 
typedef Nodo* ptrNodo; 
ptrNodo pri; 

template<class Dominio, class Rango>
bool DicListas<Dominio,Rango>::Belongs(const Dominio &d)
{
  bool retorno = false;
  if(!EsVacia())
  {
    ptrNodo aux=pri;

    while(aux!=NULL)
    {
      if(aux->dominio==d)//-------> THIS CLASS DOESN'T KNOW HOW TO COMPARE THE TYPE DOMINIO.
      {
        retorno = aux->isDef;
      }
      aux = aux->sig;
    }
  }
  return retorno;
}
like image 993
HoNgOuRu Avatar asked Sep 22 '11 17:09

HoNgOuRu


People also ask

How do you compare T types?

If you need to compare objects of type T by more or less, then the IComparable<T> interface will do. Such a comparison is necessary, for example, when sorting. If you need to compare objects of type T for equality/inequality, you can use the IEquatable<T> interface.

How do I compare two generic types in Swift?

The Swift standard library defines a protocol called Equatable , which requires any conforming type to implement the equal to operator ( == ) and the not equal to operator ( != ) to compare any two values of that type. All of Swift's standard types automatically support the Equatable protocol.

What is generic type arguments?

The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.


2 Answers

Whatever type argument you provide for the type parameter Dominio, you've to overload operator== for that type.

Suppose, you write this:

DicListas<A,B>  obj;
obj.Belongs(A());

then you've to overload operator== for the type A as:

class A
{
 public:
    bool operator == (const A &a) const
    {
       //compare this and a.. and return true or false
    }
};

Also note that it should be public if it's a member function, and better make it const function as well, so that you can compare const objects of type A.

Instead of making it member function, you can make operator== a non-member function as well:

bool operator == (const A &left, const A & right)
{
     //compare left and right.. and return true or false
}

I would prefer the latter.

like image 73
Nawaz Avatar answered Sep 27 '22 01:09

Nawaz


It reduces to defining an overload of operator== for the user-defined type:

bool operator==(const WhateverType &a, const WhateverType &b)
{
    return whatever;
}

or maybe as a member of WhateverType.

like image 40
Christian Rau Avatar answered Sep 27 '22 01:09

Christian Rau