zoukankan      html  css  js  c++  java
  • How to organize the Template Files in C++

    Normally you put class definitions in a header file and method definitions in a source file. Code that creates or uses objects of the class #includes the header file and obtains access to the method code via the linker.

    But the Template files can not organized like the non-template files. If you define the template class by organizing the declaration file (.h) and the definition file (.cpp) Normally. You will get some linking errors after building the project.

    But why templates don't work this way? 

    The reason is clear:
    When the compiler encounters template method definitions, it performs syntax checking, but doesn't actually compile the templates. 
    When the compiler encounters an instantiation of the template, such as Ruler<int> myRuler, it writes code for an int version of the  Ruler template by replacing each T in the template class definition with int. 
    So, if you don't instantiate a class template for any types in your program, then the class method definitions are never compiled.

    Then how to organize the Template Files?  There are 3 methods listed below can be used.
    1.
    You can place the method definitions directly in the same header file where you define the class itself. When you #include this file in a source file where you use the template, the compiler will have access to all the code it needs.

    2.
    You can place the template method definitions in a  separate header file that you #include in the header file with the class definitions. Make sure the #include for the method definitions follows the class definition; otherwise the code won't compile.
    But method implementations look strange in header files. 

    template <typename T>
    class Ruler
    {
        // Class definition omitted for brevity
    };
    #include " Ruler_Def.h"

    3.
    You can do by #include the method implementation source file(.cpp) in the template class definition header file, must follows the class definition.

    template <typename T>
    class Ruler
    {
        // Class definition omitted for brevity
    };
    #include " Ruler.cpp"

    When using this technique, make sure you don't add the  Ruler.cpp file to your project, because it is not supposed to be, and cannot be compiled separately; it should only be #included in a header file.

    You can actually call your file with method implementations anything you want. Some programmers like to give source files that are included an .inl extension.


  • 相关阅读:
    Asp.net 程序连接orcle如果在安装 32 位 Oracle 客户端组件的情况下以 64 位模式运行,
    Navicat 远程连接 Oracle11g 数据库报错 No listener 的问题
    springMVC中@DateTimeFormat 失效的处理
    单例设计模式中懒汉式线程安全的处理
    ajax同步请求
    vue.js在标签属性中拼接字符串
    vue.js进行遍历
    html页面之间的传值
    URL编码和解码的一个小问题(JS方法和JAVA方法)
    SolrJ的配置及使用
  • 原文地址:https://www.cnblogs.com/riskyer/p/3225846.html
Copyright © 2011-2022 走看看