使用模板成员函数时出现LNK2001错误

Getting LNK2001 error while using template member functions

本文关键字:LNK2001 错误 函数 成员      更新时间:2023-10-16

所以我没有得到外部解析,我很困惑为什么它没有正确链接

内存.cpp:https://pastebin.com/x284CFTt

内存.hpp: https://pastebin.com/9xNcVY9q

主.cpp: https://pastebin.com/hQFTmn8E

输出窗口:

1>------ Build started: Project: NAME, Configuration: Release Win32 ------
1>main.cpp
1>memory.cpp
1>main.obj : error LNK2001: unresolved external symbol "public: bool __thiscall Memory::Write<int>(unsigned __int64,int)" (??$Write@H@Memory@@QAE_N_KH@Z)
1>main.obj : error LNK2001: unresolved external symbol "public: int __thiscall Memory::Read<int>(unsigned __int64)" (??$Read@H@Memory@@QAEH_K@Z)
1>D:DesktopWorkbenchNAMEbinx86_ReleaseNAME.exe : fatal error LNK1120: 2 unresolved externals
1>Done building project "NAME.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

为什么它给我这些错误..我很困惑,我认为我正确地完成了类模板?

编译器需要模板类/函数声明和定义来创建特定类型的模板类/函数(在您的情况下int(。

有以下可能的解决方案:

  1. 将模板声明和定义添加到头文件。

  2. 将每种类型的显式模板实例化添加到模板源文件。在您的情况下,将以下行添加到memory.cpp

template int Memory::Read(DWORD64 Address);

template bool Memory::Write(DWORD64 Address, int dataBuffer);

  1. 包括模板源文件memory.cppmain.cpp。但是我认为这不是一个不错的解决方案。