overloading friend operator<< for template class

后端 未结 5 783
误落风尘
误落风尘 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:23

    Here you go:

    #include 
    #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);
    
       template friend ostream& operator<< (ostream & os, const D& rhs);
    private:
       classT d;
    };
    
    template ostream& operator<<(ostream& os, class D const& rhs)
    {
        os << rhs.d;
        return os;
    }
    
    
    int main()
    {
    
       int i1 = 1;
       int i2 = 2;
       D d1(i1);
       D d2(i2);
    
       cout << my_max(d1,d2) << endl;
       return 0;
    }
    

提交回复
热议问题