【问题标题】:C++ Templates Declaration OrderC++ 模板声明顺序
【发布时间】: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&lt;true&gt; 的类型定义未包含在 any TU 中。)

标签: c++ templates gcc


【解决方案1】:

请参阅 C++ FAQ Lite 条目[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

sayHi() 方法的定义(又名主体)必须在 temp.h 头文件中,或者在另一个包含的文件中;实例化test&lt;true&gt;时需要完整代码。

【讨论】:

    【解决方案2】:

    对于模板,声明和定义必须在同一个文件中。您可以通过将所有代码放在一个文件中(是​​否内联函数定义,由您决定)或将声明和定义分开,但在底部包含定义文件来做到这一点.h 文件.

    原来如此

    tmp.h:

    #include <iostream> 
    template <bool display>
    class test {
        public:
        void sayHi(); 
    };
    
    #include "tmp.cpp"
    

    并且 tmp.cpp 和 main.cpp 保持不变(但您不要将 tmp.cpp 交给编译器进行编译,因为它包含在 tmp.h 中)。

    许多人使用 .template 扩展名而不是 .cpp 扩展名来命名其中包含模板函数定义的文件(它让您知道它不会被编译,而且它看起来不像包含 .cpp 文件那么奇怪),但是你不必这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      相关资源
      最近更新 更多