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

前端 未结 4 1594
轻奢々
轻奢々 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: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 in the friend declaration of operator==().

    template  class Point;
    
    template 
    bool operator== (Point, Point);
    
    template 
    class Point {
        // ...
        friend bool operator== (Point, Point);
    };
    

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

提交回复
热议问题