非模板类中的模板函数 - H和CPP文件之间的划分

Joh*_*0te 5 c++ templates

我曾经(并且已经很长时间)认为你必须完全定义.h文件中的所有模板函数,以避免因模板编译过程而发生的多个定义错误(非C++ 11).

我正在阅读一个同事的代码,他有一个非模板类,其中有一个模板函数,并且他将函数声明与函数定义分开(在H中声明,在CPP中定义).它汇编并且工作正常,令我惊讶.

非模板类中的模板函数如何编译,以及如何编译模板类中的函数之间是否存在差异?有人可以解释这种差异是什么,或者我可能会感到困惑的地方?

seh*_*ehe 5

有趣的是模板的实例化方式和时间。如果可以在链接时找到实例化,则无需在头文件中看到模板定义

有时,显式实例化是这样的原因:

  • 标头:

    struct X { 
        // function template _declaration_
        template <typename T> void test(const T&);
    };
    
    Run Code Online (Sandbox Code Playgroud)
  • cpp:

    #include "X.h"
    
    // function template _definition_:
    template <typename T> 
        void X::test(const T&)
    {
    }
    
    // explicit function template _instantiation(s)_:
    template X::test<int>(const int&);    
    template X::test<std::string>(const std::string&);
    
    Run Code Online (Sandbox Code Playgroud)

使用此样本,除非在其他翻译单元中使用模板的未实例化定义,否则链接将成功