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>
。
我們需要使用surface
的distance
和lookAround
方法在我們的搜索算法Robot
的每個孩子。但在Surface<P, M>
他們是純粹的虛擬。他們只能在Surface<P, M>
的孩子中實施。
請幫幫我!也許我錯過了一些東西明顯..
哦,當然你是對的!謝謝! –