我知道这个问题是众所周知的,但这些解决方案都不适合我。我知道这个错误的一个流行原因是编译器无法在任何源文件中找到函数的定义,但我已经定义了它们的函数。
我正在使用Visual Studio 2015社区。 p>
Form.h
#pragma once
template<typename T>
class Form
{
public:
void GenerateForm(T i);
};
Form.cpp
#include "stdafx.h"
#include "Form.h"
template<typename T>
void Form<T>::GenerateForm(T i)
{
std::cout << i << endl;
}
Main.cpp的
#include "stdafx.h"
#include "Form.h"
int main()
{
Form<int> f;
f.GenerateForm(12);
return 0;
}
错误:
PrimeForm.obj : error LNK2019: unresolved external symbol "public: void __thiscall Formula<double>::GenerateForm(int)" (?GenerateForm@?$Formula@N@@QAEXH@Z) referenced in function _main
C:\Users\John\Dropbox\Visual Studio 2015\PrimeForm\Debug\PrimeForm.exe : fatal error LNK1120: 1 unresolved externals
答案 0 :(得分:0)
当您尝试编译form.cpp时,编译器不知道T
将是什么类型。因此,它无法将其编译为要与已编译的main.cpp对象文件链接的目标文件。
您需要将模板化类的所有声明和定义包含在需要它的文件中(在本例中为main.cpp文件)。
这可以简单地完成如下:
<强> Form.h 强>
#pragma once
template<typename T>
class Form
{
public:
void GenerateForm(T i);
};
#include "Form.template" /* Note include Form.template here */
<强> Form.template 强>
#include "stdafx.h"
/* Don't include form.h in this file */
template<typename T>
void Form<T>::GenerateForm(T i)
{
std::cout << i << std::endl;
}
<强>的main.cpp 强>
#include "stdafx.h"
#include "Form.h" /* including Form.h will include Form.template as well */
int main()
{
Form<int> f; /* Compiler now knows to instantiate a Form class with type Int as the template parameter */
f.GenerateForm(12);
return 0;
}
请注意,主要区别在于您不在Form.template中包含“Form.h”,但在Form.h的底部包含“Form.template”
最好使用结尾为模板化类实现文件的“.template”文件。