简体   繁体   中英

Overloaded operator> friend in class template

I am trying to have an overloaded operator> friend function within my templated class. The goal of this overloaded operator is to determine if the left array is larger than the right array, irrespective of the type. I want something along the lines of arrayInt > arrayFloat to return a boolean. However, upon defining the friend function, I get an error telling me that I have an undeclared identifier. I am utilizing XCode on Mac. Any idea how I can resolve this issue while still using the friend overloaded function?

Array.h

#ifndef Array_h
#define Array_h

#include <iostream>

template <class T> class Array;

template <class T, class S>
bool operator> (const Array<T>& arr1, const Array<S>& arr2);

template <class T>
class Array {
private:
   int arraySize;
   T * array;

public:
   Array() : arraySize(0), array(nullptr){};
   Array(int);
  ~Array();
   int getSize(){return this->arraySize;}
   void printArray();

   //error here, "S is an undeclared identifier"
   friend bool operator> (const Array<T>& arr1, const Array<S>& arr2) {
     return (arr1.arraySize > arr2.arraySize);
   }   
};

template <class T>
Array<T>::Array(int size) {
  this->arraySize = (size > 0 ? size : 0);
  this->array = new T [this->arraySize];
  for(int i=0; i<this->arraySize; i++) {
     this->array[i] = 0;
  }
}

template <class T>
Array<T>::~Array() {
  delete [] this->array;
}

template <class T>
void Array<T>::printArray() {
   for(int i=0; i<this->arraySize; i++) {
      std::cout << this->array[i] << std::endl;
   }
}

#endif /* Array_h */

main.cpp

#include "Array.h"
int main(int argc, char ** argv) {
  Array<int> arrayInt(5);
  Array<float> arrayFloat(10);

  std::cout << "Number of elements in integer array: " << arrayInt.getSize() 
  << std::endl;
  std::cout << "Values in integer array:" << std::endl;
  arrayInt.printArray();

  std::cout << "Number of elements in float array: " << arrayFloat.getSize() 
  << std::endl;
  std::cout << "Values in float array:" << std::endl;
  arrayFloat.printArray();

  bool isGreater = arrayInt > arrayFloat;

  std::cout << isGreater;

  return 0;
}

Friend declaration does not match function template, it has to be a template as well:

template<typename TT, typename TS> friend bool
operator >(const Array<TT>& arr1, const Array<TS>& arr2) {
  return (arr1.arraySize > arr2.arraySize);
} 

Actually there is no need to make it friend, define it outside and just call getSize() :

template<typename T, typename S> bool
operator >(const Array<T>& arr1, const Array<S>& arr2) {
  return (arr1.getSize() > arr2.getSize());
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM