overloading friend operator<< for template class

后端 未结 5 735
误落风尘
误落风尘 2020-11-22 01:34

I have read couple of the questions regarding my problem on StackOverflow.com now, and none of it seems to solve my problem. Or I maybe have done it wrong... The overloaded

5条回答
  •  有刺的猬
    2020-11-22 02:25

    This worked for me without any compiler warnings.

    #include 
    using namespace std;
    
    template 
    T my_max(T a, T b)
    {
      if(a > b)
        return a;
      else
        return b;
    }
    
    template 
    class D
    {
    public:
      D(classT in)
        : d(in) {};
    
      bool operator>(const D& rhs) const {
        return (d > rhs.d);
      }
    
      classT operator=(const D& rhs);
    
      friend ostream& operator<< (ostream & os, const D& rhs) {
        os << rhs.d;
        return os;
      }
    
    private:
      classT d;
    };
    
    
    int main()
    {
    
      int i1 = 1;
      int i2 = 2;
      D d1(i1);
      D d2(i2);
    
      cout << my_max(d1,d2) << endl;
      return 0;
    }
    

提交回复
热议问题