syd*_*dgm 2 c++ templates overloading friend operator-keyword
我正在尝试编写一个重载operator ==的模板类.我知道如何在课堂上学习它:
template <typename T>
class Point
{
private:
T x;
public:
Point(T X) : x(X) {}
bool operator== (Point &cP)
{
return (cP.x == x);
}
};
Run Code Online (Sandbox Code Playgroud)
但是现在我想在模板类之外实现这个目标.我读过这篇文章: 尝试重载<<运算符并使用友元函数并在我的代码中添加模板声明时出错:
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)
}
Run Code Online (Sandbox Code Playgroud)
但是我仍然收到错误: 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);
并希望它成为成员函数,会有另一个错误:
too many parameters for this function
为什么?
@Kühl的答案是声明模板化类的模板化友元函数的最宽松方法.但是,这种方法有一个不明显的副作用:所有模板实例化Point都是具有所有模板实例化的朋友operator==().另一种方法是仅使用相同类型的Point朋友进行实例化.这是通过<T>在朋友声明中添加一个来完成的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);
};
Run Code Online (Sandbox Code Playgroud)
参考文献
http://web.mst.edu/~nmjxv3/articles/templates.html