Implications of template declaration & definition

前端 未结 5 706
刺人心
刺人心 2020-12-16 00:43

From what I understand template classes and template functions (for the most part) must be declared and defined in the same header file. With that said:

  1. Are

相关标签:
5条回答
  • 2020-12-16 01:19

    A further problem is the compile times every time you change the .h (especially if it is included in a lot of places)

    0 讨论(0)
  • 2020-12-16 01:22

    One of the drawbacks encountered by implementing templates in the .h files is that any time you make a small change to the implementation, all the code that uses the template must be recompiled. There's really no way around this aside from not using templates, or declaring & defining them in the CPP file where you use them.

    You can implement templates in a seperate file, and then include that file from the .h file. Such as:

    templ.h

    template<class V> V foo(const V& rhs);
    #include "templ.inc"
    

    templ.inc

    template<class V> V foo*const V& rhs)
    {
    // do something...
    return val;
    }
    

    My personal preference is to implement templates right in the h file unless they become large, and then I'll break it up in to h and inc files.

    0 讨论(0)
  • 2020-12-16 01:22
    1. Not really. There is the export keyword, but most compilers don't support this. The only mainstream one that I know of that does support this is the Comeau compiler.
    2. If your template is part of a public API then you're exposing your code to the world. (most people don't consider this a problem, but some do. It depends on your business).
    3. Put them both in the same header file.
    0 讨论(0)
  • 2020-12-16 01:29
    1. Not really. The definition of the template must be available at compile time, since templates are instantiated depending on the template arguments you give them. This is why they must be placed in headers, so the compiler can have the code to write a new instantiation. You pretty much need a compiler with support for the export keyword.

    2. People can see your code, if that's a drawback to you. It might also be less "neat" to some people, but I don't think that's an issue.

    0 讨论(0)
  • 2020-12-16 01:34

    How To Organize Template Source Code

    Basically, you have the following options:

    • Make the template definition visible to compiler in the point of instantiation.
    • Instantiate the types you need explicitly in a separate compile unit, so that linker can find it.
    • Use keyword export (if available)
    0 讨论(0)
提交回复
热议问题