c++ - 使用模板时为 "error LNK2019: unresolved external symbol"

标签 c++ templates

<分区>

Possible Duplicate:
Why do I get “unresolved external symbol” errors when using templates?

我在代码中使用模板,但总是出现错误 LNK2019。这是我的部分代码:

方法.h

template<typename type>
void Method(Model<type>* sys);

方法.cpp

template<typename type>
void Method(Model<type>* sys){ blablabla;}

模型.h

template<typename type>
class Model{ blablabla;}

class Model1:public Model<double>{ blablabla;}

main.cpp

Model<double> *sys=new Model1();
Method(sys);

但是总是报错LNK2019: unresolved external symbol "void __cdec1 Method(class Model*)"referenced in function_main.任何人都知道我要去哪里错了吗?非常感谢!

最佳答案

模板应该在标题中实现。

方法.h

template<typename type>
void Method(Model<type>* sys){ /*Your code here*/ };

另请参阅:https://stackoverflow.com/a/495056/868546

来自 Mark Ransom :

In the .cpp file, the compiler can't guess what the template parameter will be when you use the function in other files, so it doesn't generate any actual code. The linker notices the lack of code and complains.

The usual way is to define the entire function body in the header, much as an inline function, so the compiler can emit the code when it sees the function being used with the template parameter filled in.

关于c++ - 使用模板时为 "error LNK2019: unresolved external symbol",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11512674/

相关文章:

c++ - Visual Studio 中的 std::initializer_list 歧义

c++ - C++ 模板函数可以在返回参数上重载吗?

c++ - 为什么不为模板函数隐式调用运算符转换? (C++)

c++ - 具有不同模板参数作为输入的模板类的友元函数

c++ - 使用具有一维输入的 OpenCV cv::kmeans()

c++ - 在模板类中隐藏成员函数

c++ - 是否可以浏览结构?

c++ - 行号 : Any way to use __LINE__ to return line number of input file?

c++ - 如何为boost中的节点分配标签?

c++ - 在一个程序中处理多个 QT Designer UI 文件的最佳方法是什么?