我試圖獲取模板掛,並具有以下代碼:模板參數無效
town.h
#ifndef TOWN_H
#define TOWN_H
namespace segregation {
template <typename Pos, typename Resident, template <typename> class Container>
class Town {
public:
Town();
virtual ~Town();
virtual Resident getResident(Pos address);
virtual void move(const Pos& from, const Pos& to);
virtual Container<Resident> getNeighbours(const Pos address);
};
}
#endif /* TOWN_H */
和
flat_town.h
#ifndef FLAT_TOWN_H
#define FLAT_TOWN_H
#include "town.h"
#include <array>
#include <forward_list>
#include <utility>
namespace segregation {
template<int x, int y, class R>
using TownMap = std::array<std::array<R, y>, x>;
template <typename R>
using Neighbourhood = std::forward_list<R>;
using Pos = std::pair<int, int>;
template <int x, int y, class Resident>
class FlatTown: public Town<Pos, Resident, Neighbourhood<typename Resident>> {
private:
TownMap<x, y, Resident> m_townMap;
int m_neighbourhood_size;
public:
FlatTown(TownMap<x, y, Resident> t_townMap, int t_neighbourhood_size) :
m_townMap(t_townMap), m_neighbourhood_size(t_neighbourhood_size) {};
Resident getResident(const Pos & address);
void move(const Pos & from, const Pos & to);
Neighbourhood<Resident> getNeighbours(const Pos & address);
virtual ~FlatTown();
};
}
#endif /* FLAT_TOWN_H */
我目前還沒有一個IDE,所以我通過運行
$ g++ flat_town.h
產生以下錯誤驗證正確性:
flat_town.h:18:76: error: template argument 1 is invalid
class FlatTown: public Town<Pos, Resident, Neighbourhood<typename Resident>> {
^~
flat_town.h:18:45: error: template argument 3 is invalid
class FlatTown: public Town<Pos, Resident, Neighbourhood<typename Resident>> {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我覺得這些更高級的模板非常不確定和所有幫助表示讚賞。
問候,托比亞斯
我對編譯頭文件的原因更感興趣嗎?爲什麼不包含*頭文件的源文件? –
您應該也許應該閱讀[爲什麼模板只能在頭文件中實現?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-文件) –
@Someprogrammerdude從某種意義上說,它是獲得最小樣本的自然方式(它只是斬斷一個不必要的'#include「flat_town.h」':) :) – sehe