如何使用好友函数在模板类外部重载运算符==? [英] how to overload operator == outside template class using friend function?

查看:205
本文介绍了如何使用好友函数在模板类外部重载运算符==?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个使 operator == 重载的模板类.我知道如何在课堂上使用它:

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

    template <typename T>
    class Point
    {
    private:
        T x;
    public:
        Point(T X) : x(X) {}

        bool operator== (Point &cP)
        {
            return (cP.x == x);
        }
    };

但是现在我想在模板类之外实现这一点.我已经阅读了这篇文章: 尝试重载时出现错误<<运算符并使用好友功能,并在我的代码中添加模板声明:

But now I want to achieve this outside the template class. I've read this post: error when trying to overload << operator and using friend function and add template declaration in my code:

template <typename> class Point;
template <typename T> bool operator== (Point<T>, Point<T>);
template <class T>
class Point
{
private:
    T x;
public:
    Point(T X) : x(X) {}

    friend bool operator== (Point cP1, Point cP2);
};

template <class T>
bool operator== (Point<T> cP1, Point<T> cP2)
{
    return (cP1.x == cP2.x)
}

但是我仍然出现错误:unresolved external symbol "bool __cdecl operator==(class Point<int>,class Point<int>)" (??8@YA_NV?$Point@H@@0@Z) referenced in function _main

However I still get a error: unresolved external symbol "bool __cdecl operator==(class Point<int>,class Point<int>)" (??8@YA_NV?$Point@H@@0@Z) referenced in function _main

当我带走朋友时:

friend bool operator== (Point cP1, Point cP2);

并希望它成为成员函数,则会出现另一个错误:

and want it to be member function, there would be a another error:

too many parameters for this function

为什么?

推荐答案

@Kühl的答案是声明模板类的模板朋友功能的最宽松方法.但是,这种方法有一个明显的副作用:Point的所有模板实例都是operator==()的所有模板实例的朋友.另一种选择是仅将具有相同类型Point的实例作为朋友.这是通过在operator==()的朋友声明中添加<T>来完成的.

@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);
};

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

这篇关于如何使用好友函数在模板类外部重载运算符==?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆