C + + Primer Learning notes _79_ template and generic programming--Template compiling model

Source: Internet
Author: User

templates and generics programming--Template Compilation Model

Introduction:

When the compiler sees the template definition, it does not immediately generate code. Only when a template is used , it is assumed that the compiler produces a specific type of template instance when it invokes a function template or a template-defined object .

generally, when a function is called [not a template], the compiler just needs to see the declaration of the function. Similarly, when you define an object of a class type, the class definition must be available, but the definition of the member function does not have to exist . Therefore, class definitions and function declarations should be placed in the header file , while the definitions of the normal functions and class member functions are placed in the source file .

/span> template is different: to instantiate, Span style= "color: #ff0000;" > The compiler must be able to access define the template's source code . When calling a function template or a member function of a class template , compiler requires function definition requires code that is normally placed in the source file .

Standard C + + Two models have been defined for compiling template code . In both models, the way in which a program is constructed is largely the same: class definitions and function declarations are placed in the header file , and function definitions and member definitions are placed in the source file . The difference between the two models is how the compiler uses the definition from the source file. As described in this book, all compilers support the first model, which becomes the " include " model, with only a few compilers supporting another model, the " compile separately " model.



One, including the compilation model

in the include compilation model , the compiler must see the definition of all the templates used. Generally,The ability to add a file to the header of a function template or class template by declaring a#includeindicates that the definition is available,the#includeThe introduction of source files including related definitions:

In Utilities.h#ifndef utilities_h_included#define utilities_h_included#include "utilities.cpp" template <class T >int Compare (const T &,const T &); #endif//utilities_h_included

In  utilities.cpp#include "utilities.h" template <class t>int compare (const T &val1,const t &val2) { C1/>if (Val1 < val2)        return-1;    if (Val2 < val1)        return 1;    return 0;}

This strategy allows us to keep the header and implementation files separate , but we need to ensure that the compiler can see both files when using the template's code .

Some use compilers that include models ,in particular, older compilers,able to produce multiple instances. Suppose two or more separate compiled source files use the same template,these compilers generate an instance for each template in a file . Usually,such a method means that a given template will be instantiated more than once . At the time of the link ,or in the pre-link phase,the compiler chooses one instantiation and discards the others . In such a case,Suppose there are many files that instantiate the same template,performance is significantly reduced at compile time. For many applications,such compile-time performance reductions are unlikely to be a problem on modern computers,but,in a large system environment, Compile-time selection issues can become very important .

such compilers typically support certain mechanisms , avoid the overhead of compiling in multiple instantiations of the same template. The compiler optimizes compile-time performance in different ways. Assuming that the compile time of the program using the template is difficult to bear , Consult the compiler's User guide to see what support your compiler can provide to avoid unnecessary instantiation .



Second, compile the model separately

In the separate compilation model , the compiler will track the relevant template definitions for us. However, we have to let the compiler know to remember the given template definition and be able to use exportkeyword to do it.

Export keyword can indicate that a given definition may need to be instantiated in other files . In a program , A template can only be defined as a single export . The compiler calculates how to position the template definition when it is necessary to generate these instantiations. exportkeyword does not have to appear in the template declaration.

in general, we indicate in the definition of a function template that the function template is an exported ,This is done through the keywordTemplate previously includedExportkeyword and the realization of:

In  utilities.hexport template <typename type>int compare (const type &VAL1,CONST type &val2)/***/

the declaration of this function template should be placed in the header file as usual and the declaration does not have to be specified Export .



using the class template Exportmore complicated. Usually, class declarations must be placed in the header file ,the class definition body in the header file should not use keyword export,assuming that the header file was usedExport, The header file can only be used by one source file in the program .

instead , should be used in the implementation file of the class export:


In implementation fileexport template <class type> class Queue; #include "Queue.h"//...

the members of the exported class declare themselves as exported. It is also possible to declare individual members of a class template as exported ,in such a case,keywordExportdoes not specify the class template itself,Instead, it is specified only on the specific member definition that is exported. the definition of the exported member function does not have to be visible when using members . The definition of a discretionary non-exported member must be treated as if it were included in the model: the definition should be placed in the header file that defines the class template .

P544 exercises 16.27//in middle.h#ifndef middle_h_included#define middle_h_included#include <vector> #include < Algorithm>using namespace Std;template <typename type>bool Middle (const vector<type> &,Type &); #include "middle.cpp" #endif//middle_h_included

In Middle.cpp#include "middle.h" template <typename type>bool middle (const vector<type> &vec,type &val) {    vector<type> tmp (VEC);    Sort (Tmp.begin (), Tmp.end ());    if (tmp.size ()% 2 = = 0)    {        return false;    }    TypeName Vector<type>::iterator index =        tmp.begin () + tmp.size ()/2;    if (*index > * (index-1) && * (Index) < * (index + 1))    {        val = *index;        return true;    }    return false;}

In Main.cpp#include <iostream> #include "middle.h" using namespace Std;int Main () {    int ia[] = {1,2,3,4,5,6,7} ;    int ai[] = {1,2,3,4,5,6};    Vector<int> IVEC1 (Ia,ia + 7), IVEC2 (Ai,ai + 6);    int Val;    if (middle (ivec1,val))    {        cout << middle: "<< val << endl;    }    else    {        cout << "No middle!" << Endl;    }    if (middle (ivec2,val))    {        cout << middle: "<< val << endl;    }    else    {        cout << "No middle!" << Endl;    }} /** Note: The g++ compiler supports including the model * but cannot include the template implementation file in project, * otherwise it will cause a compilation error! */

C + + Primer Learning notes _79_ template and generic programming--Template compiling model

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.