标签:int 编译器 otto lin tom 解决 compile 声明 bag
如果将类模板的声明和实现写在两个独立的文件中,在构建时会出现“error LNK2019: 无法解析的外部符号 ”的错误。
解决方法有:
原因在于模板类和模板函数在使用的时候才会被实例化。当模板被使用时,编译器需要函数所有的实现代码,来用合适的类型(模板参数)去构建正确的函数。但是如果将函数实现在单独的源文件中,这些文件是不可见的,因而会出错。
下面是摘自 StackOverflow的回答:
Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:
template<typename T> struct Foo { T bar; void doSomething(T param) {/* do stuff using T */ } }; // somewhere in a .cpp Foo<int> f;
When reading this line, the compiler will create a new class (let‘s call it FooInt), which is equivalent to the following:
struct FooInt { int bar; void doSomething(int param) {/* do stuff using int */ } }
Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn‘t be accessible, and therefore the compiler wouldn‘t be able to instantiate the template.
参考:
CSDN:模板类 error LNK2019: 无法解析的外部符号
StackOverflow:Why can templates only be implemented in the header file?
标签:int 编译器 otto lin tom 解决 compile 声明 bag
原文地址:http://www.cnblogs.com/VVingerfly/p/6124917.html