how to overload operator == outside template class using friend function?

前端 未结 4 1599
轻奢々
轻奢々 2021-01-15 16:00

I\'m trying to write a template class which overloads operator==. I know how to get it inside the class:

    template 
            


        
相关标签:
4条回答
  • 2021-01-15 16:13

    This is a tricky issue: the friend declaration in the class will define a different friend function for each instantiation of your class. In other words, Point<int> and Point<double> will give rise to 2 different non-template friend functions. On the other hand, the outside function is a template function, not related to the friend inside the class. Solution: define the friend function inside the class. Due to friend name injection, it will be found successfully by ADL.

    0 讨论(0)
  • 2021-01-15 16:15

    The declaration of the operator==() is a template. The declaration made a friend is not a template but a non-template. To make the template operator==() a friend you need to make the friend declaration a template, too:

    template <typename T> class Point;
    
    template <typename S>
    bool operator== (Point<S>, Point<S>);
    
    template <typename T>
    class Point {
        // ...
        template <typename S>
        friend bool operator== (Point<S>, Point<S>);
    };
    
    0 讨论(0)
  • 2021-01-15 16:19

    You have to put friend classes within each other, as well as in themselves. The Real one is named syntactically the same without replacing expressions. So friend bool operator==(P<T>,P<T>); goes in both of the classes. So put friend before bool in the class T :-)

    0 讨论(0)
  • 2021-01-15 16:35

    @Kühl's answer is the most permissive approach to declare a templated friend function of a templated class. However, there is one unapparent side effect of this approach: All template instantiations of Point are friends with all template instantiations of operator==(). An alternative is to make only the instantiation with the same type of Point a friend. Which is done by adding a <T> in the friend declaration of operator==().

    template <typename T> class Point;
    
    template <typename S>
    bool operator== (Point<S>, Point<S>);
    
    template <typename T>
    class Point {
        // ...
        friend bool operator==<T> (Point, Point);
    };
    

    References
    http://web.mst.edu/~nmjxv3/articles/templates.html

    0 讨论(0)
提交回复
热议问题