错误"纯虚函数叫"在模板派生类中

时间:2016-11-29 10:56:24

标签: c++ templates inheritance pure-virtual

我需要制作一般Robot来查找一般Surface的路径。

所以这是我的Surface界面:

template <typename P>
class Surface {
public:
    virtual int distance(const P& from, const P& to) const = 0;
    virtual bool check(const vector<P>& path, const P& from, const P& to) const = 0;
    virtual vector<P> lookAround(const P& at) const = 0;
};

在这里,我创建了一个简单的PlanarSurface

class PlanarSurface : public Surface<pair<int, int>> {
public:
    using point_type = pair<int, int>;
    int distance(const point_type& from, const point_type& to) const override {
        return to.first - from.first + to.second - from.second;
    }

    bool check(const vector<point_type>& path, 
               const point_type& from, 
               const point_type& to) const override {
        return true; // there would be the check
    }

    vector<point_type> lookAround(const point_type& at) const override {
        vector<point_type> result;
        //...
        return result;
    }
};

现在我创建一个抽象类Robot,以便每个用户实现的机器人都可以扩展它:

template <typename P>
class Robot {
public:
    Robot(const Surface<P>& s): surface(s) {}
    vector<P> findPath(const P& from, const P& to) {
        auto path = searchPath(from, to);
        if (surface.check(path, from, to)) {
            return path;
        }
        throw runtime_error("path not found or incorrect");
    }
private:
    virtual vector<P> searchPath(const P& from, const P& to) = 0;
protected:
    const Surface<P>& surface;
};

searchPath私有方法将负责自定义搜索算法,该算法在Robot的子项中定义。 假设我有一个:

template <typename P>
class MyRobot: public Robot<P> {
public:
    MyRobot(Surface<P> m): Robot<P>(m) {}
private:
    vector<P> searchPath(const P& from, const P& to) override {
        vector<P> result;
        // ...
        // use one of surface's virtual methods
        auto dist = this->surface.distance(from, to); // Pure virtual function called!
        cout << dist << endl;
        // ...
        return result;
    }
};

最后是main函数:

int main(const int argc, const char **argv) {
    PlanarSurface plane;
    MyRobot<pair<int, int>> robot(plane);
    robot.findPath({1,2}, {3,4});
    return 0;
}

所以问题是,由于对surface的引用存储在基类Robot类中,我们无法指定它的类型,其中一些派生自Surface类。因此,引用的类型只能是Surface<P, M>

我们需要在surface的每个孩子的搜索算法中使用distance的{​​{1}}和lookAround方法。但在Robot中,它们是纯粹的虚拟。它们只能在Surface<P, M>的孩子中实现。

请帮帮我!也许我错过了一些明显的东西......

1 个答案:

答案 0 :(得分:4)

错误在于:

MyRobot(Surface<P> m) : Robot<P>(m) {}
        ^^^^^^^^^^^^ value

将其更改为接受引用

MyRobot(Surface<P>& m) : Robot<P>(m) {}

有趣的是,MSVC和gcc都按照

的方式诊断出这个问题
  

无效的抽象参数

虽然clang甚至没有发出警告(在写这篇文章的时候--4.0)