链接器错误"未解析的外部符号":使用模板

Roh*_*bhu 8 c++ templates qt4 linker-errors visual-c++

我有一个基于模板的类[Allotter.h和Allotter.cpp]:

template <typename allotType> class Allotter {
public:
 Allotter();
 quint32 getAllotment(allotType*);
 bool removeAllotment(quint32, int auto_destruct = 0);

private:
 QVector<QPair<quint32, allotType*>> indexReg;
 int init_topIndex;
};
Run Code Online (Sandbox Code Playgroud)

它的用法显示为[ActiveListener.h和ActiveListener.cpp]:

class ActiveListener: public QObject {
 Q_OBJECT

public:
 ActiveListener();

private slots:
    void processConnections();
    void readFromSocket(int);

private:
 QTcpServer* rootServer;
 QSignalMapper* signalGate;
 Allotter<QTcpSocket> TcpAllotter;
};
Run Code Online (Sandbox Code Playgroud)

我没有显示完整的定义,因为它并不重要.问题是当我编译时,所有文件都正确编译.这些文件位于VC++项目中.早些时候,当我没有使用基于模板的方法时Allotter,一切都在编译和链接很好.但是现在,我收到了这个错误:

1>ActiveListener.obj : error LNK2019: unresolved external symbol "public: __thiscall Allotter<class QTcpSocket>::Allotter<class QTcpSocket>(void)" (??0?$Allotter@VQTcpSocket@@@@QAE@XZ) referenced in function "public: __thiscall ActiveListener::ActiveListener(void)" (??0ActiveListener@@QAE@XZ)
1>ActiveListener.obj : error LNK2019: unresolved external symbol "public: unsigned int __thiscall Allotter<class QTcpSocket>::getAllotment(class QTcpSocket *)" (?getAllotment@?$Allotter@VQTcpSocket@@@@QAEIPAVQTcpSocket@@@Z) referenced in function "private: void __thiscall ActiveListener::processConnections(void)" (?processConnections@ActiveListener@@AAEXXZ)
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,构造函数ActiveListener::ActiveListener()根本没有任何引用Allotter<QTcpSocket>::Allotter().然而,第二个参考确实存在.但我不明白为什么链接器无法解析此外部符号.

错误出现之前的构建输出是:

1>Moc'ing ActiveListener.h...
1>Compiling...
1>stdafx.cpp
1>Compiling...
1>ActiveListener.cpp
1>Allotter.cpp
1>moc_ActiveListener.cpp
1>main.cpp
1>Generating Code...
1>Linking...
Run Code Online (Sandbox Code Playgroud)

我不明白这些是否相关,主要是因为以前所有这些都是完美的.只是在我使用模板后导致问题.任何帮助将不胜感激.非常感谢.

小智 17

您无法将模板拆分为.h和.cpp文件 - 您需要将模板的完整代码放在.h文件中.

  • 除非你使用`export`,它只适用于童话故事. (5认同)