Home > Net >  Overloading class template operator == such that it is defined on different data-type objects C
Overloading class template operator == such that it is defined on different data-type objects C

Time:12-14

I have to code a class template arrayPlus where objects are arrays of a type T.

The operator == must be overloaded so that two objects of the class are equal iff they are of the same type and return false otherwise.

I have overloaded it but it seems to only be defined on data of the same type. How can I define it so that it works of different data-type arrays?

Here is the code for the class template (including the operator overloading)

#include <typeinfo>

using namespace std;

template<class T> class arrayPlus {
    T* type;
    int nbElem;

public:
    arrayPlus(int n) {
        nbElem = n;
        type = new T[nbElem];
    };

    bool operator == (arrayPlus& const obj) {
        return (typeid(this->type) != typeid(obj.type));
    }
};

And, in the main, this code have to compile and return false

int main(){
   #include <iostream>
#include <typeinfo>

#include "arrayPlus.h"

using namespace std;

int main() {
    arrayPlus<bool> arrBool(3);
    arrayPlus<int> arrInt(3);
    arrBool == arrInt;//<-- error
}
        

I get an error at the == saying

no operator "==" match these operands 
    operand types are: arrayPlus<bool> == arrayPlus<int>

CodePudding user response:

As mentioned in comments you should note that tableauPlus<bool> and tableauPlus<int> are two distinct types. And your operator== can only compare tableauPlus<T> with a tableauPlus<T>.

Note that when you wrote tablaeuPlus inside definition of tebleauPlus<T> it actually refers to tableauPlus<T>. Its just short hand way for it. Your bool operator == (tableauPlus const&); is actually bool operator == (tableauPlus<T> const&);.

You want a templated operator== to be able to compare a tableauPlus<T> to a tableuPlus<U>.

As non-member:

#include <iostream>
#include <type_traits>

template<typename T>
struct foo {
    int value = 42;
};

template <typename T,typename U>
bool operator==(const foo<T>& a,const foo<U>& b) {
    if constexpr (!std::is_same_v<T,U>) return false;
    return a.value == b.value;
}


int main() {
    foo<int> a;
    foo<bool> b;

    std::cout << (a==b);
    std::cout << (a==a); 
}

CodePudding user response:

With injected class name, you define only operator == with both operand of the same type:

template <class T>
class tableauPlus {
public:
    
    bool operator == (tableauPlus const&); // tableauPlus<T>
};

You need extra overload:

template <typename T, typename U>
bool operator == (tableauPlus<T> const&, tableauPlus<U> const&){ return false; }

And your existing overload would be

/*OPERATOR OVERLOAD*/
template<class T> 
inline bool tableauPlus<T>::operator==(tableauPlus<T> const& obj) {
    return this->firstIndex == obj.firstIndex && this->lastIndex == obj.lastIndex;
}
  • Related