【发布时间】:2011-11-02 14:25:12
【问题描述】:
我正在尝试编译一个实例化的最小示例 一个模板类。该示例在特定顺序时编译得很好 的声明被保留,否则失败。
温度.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:(.text+0x3a): undefined reference to `test::sayHi()'
但是,当我在 main.cpp 中执行 #include "temp.cpp" 而不是 #include "temp.h" 时,示例会编译 文件,以便编译器首先读取 temp.h 中的类声明,然后 看到 temp.cpp 的内容,然后才看到 main.cpp 的内容。
当我使用非模板类时,只包含 .h 文件就可以了 在 main.cpp - 这里出了什么问题?请注意,包含 temp.cpp 在我的 Makefile 中,所以编译器绝对不应该忘记它。 感谢您的帮助。
【问题讨论】:
-
一行总结:模板不是类型,type定义必须包含在(至少)一个翻译单元中。 (在您的代码中,
test<true>的类型定义未包含在 any TU 中。)