2017-10-11 92 views
0

我试图获取模板挂,并具有以下代码:模板参数无效

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>> { 
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

我觉得这些更高级的模板非常不确定和所有帮助表示赞赏。

问候,托比亚斯

+1

我对编译头文件的原因更感兴趣吗?为什么不包含*头文件的源文件? –

+0

您应该也许应该阅读[为什么模板只能在头文件中实现?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-文件) –

+1

@Someprogrammerdude从某种意义上说,它是获得最小样本的自然方式(它只是斩断一个不必要的'#include“flat_town.h”':) :) – sehe

回答

1

您指定模板模板参数不正确。只需指定模板的名称,即

class FlatTown: public Town<Pos, Resident, Neighbourhood> { 
+0

当然!谢谢!顺便说一句,我来自斯卡拉,我不知道我正在做C++。你知道这种通用编程是否可行吗? – user25470

+0

@ user25470如果不知道使用场景,很难说。无论如何,目前的代码似乎很好。 – songyuanyao

+0

这个想法是为了模拟城市内部的移动,看看居民之间是否存在相似性偏好,是否会出现自然分离现象,即如果A类居民更偏好其偏好,则A类居民将离开另一个居民区。由于我想稍微尝试一下,我希望基地town.h尽可能通用 – user25470