我有一个包含以下虚方法的类:
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
应该只接受point2D
类型的参数。我怎样才能做到这一点?
这是我在执行上述操作之前尝试过的:
virtual double distTo(point& other) = 0;
但是,当我在 point2D
类中覆盖此方法并尝试将参数替换为 point2D
类型之一时,我遇到了编译器错误。
谢谢你的时间
最佳答案
这听起来像是 Curiously Recurring Template Pattern。此外,这与动态间接寻址完全不兼容,因为编译器无法静态验证动态类型(显然)。但 CRTP 只能用于实现功能,而不能声明它。
template<typename T> class Point {
public:
double distTo(T other) {
/* stuff */
}
};
class Point2D : public Point<Point2D> {
// distTo automatically defined
};
从根本上说,您尝试声明的接口(interface)是完全不可能的,因为您要求编译器对动态类型进行静态类型检查。没有任何解决方案可以提供您想要的所有属性。
关于C++虚函数覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29581389/