我对模板类的显式实例化似乎不起作用
|
我编写了一个简短的程序来测试模板类的显式实例,如下所示:
#include <iostream>
template <class T>
struct less_than_comparable {
friend bool operator>=(T const& a, T const& b) {
return !(a < b);
}
};
class Point {
friend bool operator<(Point const& a, Point const& b) {
return a.x_ < b.x_;
}
public:
Point(int x) : x_(x) {}
private:
int x_;
};
template struct less_than_comparable<Point>;
//Here I explicitly instantiate a template class expecting that
//less_han_comparable<Point> would export opeartor>=() for class Point to the global
//namespace, and then the p1 >= p2 statement will work as expected.
int main() {
using namespace std;
Point p1(1), p2(2);
cout << (p1 < p2) << endl;
cout << (p1 >= p2) << endl; //But I have a compiler error here saying that
//no match for ‘operator>=’ in ‘p1 >= p2’
}
我知道如果我从less_than_comparable继承Point,那么代码将通过编译。
但是我的问题是,如果我使用显式实例化,为什么它不起作用?
我使用在Ubuntu 10.04上运行的G ++ 4.4.5。
任何意见将不胜感激。谢谢。
没有找到相关结果
已邀请:
4 个回复
购藏盗码韦
(即
)中呼叫
时。 ADL在
的命名空间中寻找匹配功能,但是
没有此功能。 如果您从
继承
,则
成为
命名空间的一部分,ADL可以在此处找到它。 您可以检查一下,此处没有朋友名称的注入。
遣莫捅炭
不是您定义
的模板类。 如果要编译此代码,请在Point类中也定义
。注意,
和
与
没有关系。 作为旁注,为什么要以
的名称为\“大于等于\”运算符定义运算符?
烫珊
岭取
忘记该类,而只是使其成为全局函数即可。而且您不需要显式的模板实例化。实际上,我唯一看到它使用的是您在库中声明了模板类并在另一个项目中使用了模板类,显然您在这里没有这样做。