C++虚函数覆盖

标签 c++ inheritance polymorphism abstract-class

我有一个包含以下虚方法的类:

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’

计划是通过创建更具体的实例来专门化类,例如 point2Dpoint3D。但是,我只希望该函数适用于同一类的类型。所以如果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/

相关文章:

c++ - 回调函数 : difference between void(*func)(int) and void(func)(int)

c++ - typeinfo 和dynamic_cast 外部未解析

javascript - 使用 Object.create 进行继承?

c++ - 使子类可以调用彼此的共享成员变量

c++ - 通过指向其非模板父类的指针将模板值分配给类模板

c++ - UTF-16 到 UTF8 与 WideCharToMultiByte 问题

c++ - 如何为使用Clang LLVM编译的C++代码生成图形代码配置文件报告?

c++ - 在 memcpy 缓冲区 UB 上使用 reinterpret_cast 吗?

java - 垃圾收集的对象数

使用 shared_ptr 函数模板的 C++ 实例化