我有一个包含以下虚拟方法的类:
struct point {
template<typename T>
virtual typename std::enable_if<std::is_base_of<point, T>::value, double>::type distTo(T &other) const = 0;
};
上面的方法不起作用,因为:
error: templates may not be ‘virtual’
计划是通过制作更具体的实例,如point2D
,point3D
。但是,我只希望该函数使用相同类的类型。因此,如果要point2D
在哪里继承此类,则该方法distTo
应仅采用type的参数point2D
。我该怎么做?
这是我在执行上述操作之前尝试过的方法:
virtual double distTo(point& other) = 0;
但是,当我在point2D
类中重写此方法并尝试用type之一替换参数时point2D
,我遇到了编译器错误。
谢谢你的时间
我认为您的要求对诸如C ++之类的静态类型语言毫无意义。
考虑一下您将如何使用虚拟功能:
point2d p1, p2;
point3d p3;
point &p = p1;
p.distTo(p2); //ok?
p.distTo(p3); //error?
根本不可能,因为在编译时,编译器仅在运行时才知道p
是apoint2d
还是a的引用point3d
。
如果做错了,可以添加一个显式的强制转换和运行时断言,但是我认为这没有什么意义。只需做:
struct point { /*...*/ };
struct point2d : point {
double distTo(const point2d &other);
};
struct point3d : point {
double distTo(const point3d &other);
};
并且不要distTo
使用基本point
引用进行调用。
更新:如果您知道列表是同类的,但不知道基数,则可以执行以下操作:
struct point {
virtual double distTo(const point &other) =0;
};
struct point2d : point {
double distTo(const point2d &other) { /*...*/ }
virtual double distTo(const point &other) {
const point2d &other2 = static_cast<const point2d &>(other);
return distTo(other2);
}
};
struct point3d : point {
double distTo(const point3d &other) { /*...*/ }
virtual double distTo(const point &other) {
const point3d &other3 = static_cast<const point3d &>(other);
return distTo(other3);
}
};
但是要当心!如果调用point::distTo
错误的对象,结果将是不确定的!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句