#include <iostream>
#include <fstream>
#include <type_traits>
#include <Windows.h>
#include "abase.h"
using namespace std;
class Storage {
string _path;
public:
Storage(string path);
~Storage() = default;
template <typename T >
bool writeFile(string fileName,
typename enable_if<is_base_of<ABase, T>::value, T >::type* data);
}
...定义
#include "storage.h"
Storage::Storage(string path)
{
this->_path = path;
}
template <typename T >
bool Storage::writeFile(string fileName,
typename enable_if<is_base_of<ABase, T>::value, T >::type* data){
return true;
}
链接器我仍然收到错误:
LNK2019未解析的外部符号“public:bool __thiscall Storage :: writeFile(class std :: basic_string,class std :: allocator&gt;,class AFile *)“ (?? $ WriteFile的@ VAFile @@@寄存@@ QAE_NV?$ basic_string的@ DU?$ char_traits @ d @ @@ STD V'$分配器@ d @ @@ 2 STD @@ PAVAFile @@@ Z) 在函数_main
中引用
如果代码看起来正确,为什么我会得到它。它在类中的方法的通用定义和我试图约束传递给方法的类类型。 而AFile则继承自ABase。
ABase是抽象类。
主要用法:
Storage* s = new Storage("C:\\aPath...");
AFile* afile = new AFile();
s->writeFile<AFile>("a.txt", afile);
答案 0 :(得分:0)
要解决链接错误,您可以在Storage.cpp中显式实例化[1]模板成员函数,如下所示:
template
bool Storage::writeFile<AFile>(string fileName,
enable_if<is_base_of<ABase, AFile>::value, AFile>::type* data);
所以编译器创建了函数,链接器可以找到。
最好在标题文件中移动定义 - Why can templates only be implemented in the header file?。