开发者

Linking a template class using another template class (error LNK2001)

开发者 https://www.devze.com 2023-01-03 07:33 出处:网络
I implemented the \"Strategy\" design pattern using an Abstract template class, and two subclasses. Goes like this:

I implemented the "Strategy" design pattern using an Abstract template class, and two subclasses. Goes like this:

template <class T> 
class Neighbourhood {
public:
  virtual void alter(std::vector<T>& array, int i1, int i2) = 0;
};

and

template <class T> 
class Swap : public Neighbourhood<T> {
public:
  virtual void alter(std::vector<T>& array, int i1, int i2);
};

There's another subclass, just like this one, and alter is implemented in the cpp file. Ok, fine! Now I declare another method, in another class (including neighbourhood header file, of course), like this:

void lSearch(/*parameters*/, Neighbourhood<LotSolutionInformation> nhood);

It compiles fine and cleanly. When starting to link, I get the following error:

1>SolverFV.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall lsc::Neighbourhood<class LotSolutionInformation>::alter(class std::vector<开发者_如何学编程class LotSolutionInformation,class std::allocator<class LotSolutionInformation> > &,int,int)" (?alter@?$Neighbourhood@VLotSolutionInformation@@@lsc@@UAEXAAV?$vector@VLotSolutionInformation@@V?$allocator@VLotSolutionInformation@@@std@@@std@@HH@Z)


There's another subclass, just like this one, and alter is implemented in the cpp file.

No can do - it's got to be in the header.


It seems it was a pretty rookie mistake. Since Neighbourhood is an abstract class, I must use it always as a pointer (EDIT: or a reference), since it must never be instantiated.

Changed signatures and it worked fine.

EDIT: Also, thanks to Neil, I know "it's got to be in the header".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号