Operator overloading on class templates

后端 未结 5 1585
孤城傲影
孤城傲影 2020-12-01 05:47

I\'m having some problems defining some operator overloads for template classes. Let\'s take this hypothetical class for example.

template 
cl         


        
5条回答
  •  北海茫月
    2020-12-01 06:28

    You need to say the following (since you befriend a whole template instead of just a specialization of it, in which case you would just need to add a <> after the operator<<):

    template
    friend std::ostream& operator<<(std::ostream& out, const MyClass& classObj);
    

    Actually, there is no need to declare it as a friend unless it accesses private or protected members. Since you just get a warning, it appears your declaration of friendship is not a good idea. If you just want to declare a single specialization of it as a friend, you can do that like shown below, with a forward declaration of the template before your class, so that operator<< is regognized as a template.

    // before class definition ...
    template 
    class MyClass;
    
    // note that this "T" is unrelated to the T of MyClass !
    template
    std::ostream& operator<<(std::ostream& out, const MyClass& classObj);
    
    // in class definition ...
    friend std::ostream& operator<< <>(std::ostream& out, const MyClass& classObj);
    

    Both the above and this way declare specializations of it as friends, but the first declares all specializations as friends, while the second only declares the specialization of operator<< as a friend whose T is equal to the T of the class granting friendship.

    And in the other case, your declaration looks OK, but note that you cannot += a MyClass to a MyClass when T and U are different type with that declaration (unless you have an implicit conversion between those types). You can make your += a member template

    // In MyClass.h
    template
    MyClass& operator+=(const MyClass& classObj);
    
    
    // In MyClass.cpp
    template  template
    MyClass& MyClass::operator+=(const MyClass& classObj) {
      // ...
      return *this;
    }
    

提交回复
热议问题