2016-11-29 140 views
3

我需要制作一般的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; 
}; 

There 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>

我们需要使用surfacedistancelookAround方法在我们的搜索算法Robot的每个孩子。但在Surface<P, M>他们是纯粹的虚拟。他们只能在Surface<P, M>的孩子中实施。

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

回答

4

的错误是在这里:

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

改变它接受一个参考,而不是

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

有趣的是这两个MSVC和GCC沿

线诊断此问题

抽象参数无效

虽然铿锵甚至没有发出关于此的警告(在写这篇文章的时候 - 4.0)

+1

哦,当然你是对的!谢谢! –

相关问题