我想编译一个最小的例子,它实例化了一个模板类 。该示例在保留声明的某个订单 时编译正常,否则失败。C++模板声明顺序
temp.h:
#include <iostream>
template <bool display>
class test {
public:
void sayHi();
};
temp.cpp:
#include "temp.h"
template <bool display>
void test<display>::sayHi() {
if (display) std::cout << "Hi";
}
main.cpp中:
#include <iostream>
#include "temp.h"
int main() {
test<true> myobject;
myobject.sayHi();
return 0;
}
这是如何包括类标准。 在GCC 4.4.6,这个失败,错误 的main.cpp :(文本+ 0x3a):未定义参考`测试:: sayHi的()”
然而,示例编译当我做了的#include “temp.cpp”代替main.cpp 文件中的#include“temp.h”,以便编译器首先读取temp.h中的类声明,然后 将看到temp.cpp的内容,并且仅在此之后main.cpp中。
当我使用非模板类时,它可以很好地在main.cpp中包含.h文件 - 这里出了什么问题?请注意,temp.cpp包含在我的Makefile中的 ,所以它肯定不应该被编译器遗忘。 感谢您的帮助。
http://stackoverflow.com/questions/3705740/c-lnk2019-error-unresolved-external-symbol-template-classs-constructor-and/3705774#3705774 –
单行摘要:模板不是类型,并且*类型*定义必须包含在(至少)一个翻译单元中。 (在你的代码中,'test'的类型定义不包含在* any * TU中。) –