Instantiation and materialization of C + + templates

Source: Internet
Author: User
Tags function definition

The template declaration Template<typename/class T> TypeName is added to the C + + standard after the recent class.

General template, materialized template, non-template function priority call order.

Non-template functions (normal functions) > materialized template functions > General Templates

Display materialization:

Materialization represents the overriding function template for a particular type, and the meaning of the Declaration is to use a separate, specialized function definition to generate a function definition for a particular type.

Why should there be display materialization? Handling Special cases that template functions cannot handle. Explicit materialization of explicit materialization is also based on function templates, but on the basis of function templates, add a specific type of materialized function that is different in implementation.

Displays materialized declarations that contain <> after the keyword template;.

Such as:

    1. template<> void swap<job> (Job &j1, job &j2);

vs2013 does not support:

  1. void swap (any &a, any &b);
  2. struct job
  3. {
  4. Char name[40];
  5. double salary;
  6. int floor;
  7. };
  8. template<> void swap<job> (Job &j1, job &j2);
  9. void Show (Job &j);
  10. int main () {
  11. using namespace std;
  12. template void swap<job> (Job &, Job &);
  13. int i = ten, j = 20;
  14. Swap (I, j);
  15. return 0;
  16. }
  17. template<TypeName Any>
  18. void swap (any &a, any &b) {
  19. any temp;
  20. temp = A;
  21. A = b;
  22. b = temp;
  23. }
  24. template<> void swap<job> (Job &j1, Job &j2) {
  25. double temp_sal;
  26. Temp_sal = j1.salary;
  27. J1.salary = j2.salary;
  28. J2.salary = Temp_sal;
  29. }

Display instantiation:

Example: a function call Swap (I,J) causes the compiler to generate an instance of swap () that uses the int type.

Syntax: The type required by the declaration is indicated by the <> symbol, and the keyword template is added before the declaration:

Why should I have a display instantiation? in fact, the compiler uses the function only when it wants to invoke the function, and if you do not use display instantiation, the template consumes performance to deduce which type of function is used, which increases the burden of the program when it is used, and the function selection is processed at compile time, using the display instantiation.

Example of instantiation:

      1. Template void swap<int> (int, int);

Note: An error occurs when attempting to instantiate and display materialized declarations using the same type of display in the same file (or conversion unit).

Recommendation: You can use the function call to display the instantiation directly instead of using the display instantiation declaration.

Such as:

Template <typename t>t Add (T x,t y) {      return x+y;      } int main () {     int i1=2,i2=3;     Add<int> (I1,I2);     template int add<int> (I1,I2);//try to replace the bank return 0 with the line above     ;    }

  

Exemplary code:

 @file templetadd.cc//@author Alex ([email protected])// /@date 2018-06-19 21:42:20///**********************************************/#include <string.h> #include <  iostream>using std::cout;using std::endl;//Template--type parametric--code generator//instantiation (template argument derivation)//function template--template function//< > Template parameter list//1, use class or TypeName to set type parameter//2, non-type parameter, constant expression (integer data) template <class t>t Add (T x,t y) {return x + y;}    #if 0template int add<int> (int x,int y)//{cout<< "Template display instantiation" <<endl; return x+y;}  #endiftemplate <> int add<int> (int x,int y)//equivalent to template<>int add (int x,int y) {cout<< "template    Show materialized "<<endl; return x+y;} The special version of the template, cannot be used independently of the general version//for special cases, but must be in the general version of the existence of the template<>//can be used to comment out this line is also possible, it indicates that the following method is overloaded with the template function Const char* Add (    Const CHAR*LHS,CONST char* rhs) {char*tmp = new Char[strlen (LHS) +strlen (RHS) +1] ();    strcpy (TMP,LHS);    strcat (TMP,RHS); return TMP;} #if 0//General LetterNumber and function templates can be overloaded//normal function precedence higher than the template function int Add (int x,int y)//can be overloaded because the formal parameter type is different {return x + y;} #endif//function template and function template can also be overloaded with//function template Declaration template <typename t>t Add (T x,t y,t z);//c++11 features//c++11 previous versions for function templates, Non-type parameter cannot set default value//non-type parameter must be shaping class data (bool, char, int, long, long Long) template <typename t,int num=10>int func (T x,t y) {Retu RN X*y*num;}    int main () {int a=3,b=4;    Double c1=1.2,c2=2.3,c3=4.9;    Char ch1= ' a ', ch2=2;    Template Char add<char> (char X,char y);//error Func (CH1,CH2) when attempting to instantiate and display materialized declarations using the same type of display in the same file (or conversion unit);    const char *p1= "Hello";    const char *p2= "good"; cout << "int + int =" << Add (A, b) << endl;//implicitly instantiates cout << "double + double =" << add&lt    ;int> (C1,C2) << endl;//display instantiation cout << "char + char =" << Add (CH1,CH2) << Endl;    cout << "double + double =" << Add (C1,C2,C3) << Endl; cout << "int + int =" << func<double,8> (A, b) << endl;//the way constants are passed//cout << "a+d1=" << Add (A,C1) << endl;//error, template parameters must be strictly consistent cout << Add (P1,P2) << Endl; return 0;} Implementation of function Templates template <class t>t Add (T x,t y,t z) {return x +y + z;}

  

Summarize:

implicit instantiation refers to the compiler not generating declarations and defining instances of a template until the template is used. The compiler generates instances of the appropriate type based on the template definition only when the template is used.  such as: int i=0, J=1;swap (i, j); The compiler implicitly generates a function definition for swap<int> (int &a, int &b) based on the type of the parameter i,j. The array<int> arval;//compiler implicitly generates array<int> class declarations and class function definitions based on type parameters.

explicit instantiation : When you explicitly instantiate a template, the compiler generates a template instance based on the type you specify explicitly, before using the template. As shown earlier, instantiate (explicit instantiation) template functions and template classes. The format is: Template typename function<typename> (argulist), template class classname<typename>; explicit instantiation only need to declare, No redefinition is required. The compiler implements instance declarations and instance definitions based on templates.

display materialization : For some special types, the template implementation may not be appropriate, and the implementation needs to be redefined, and display materialization (Explicite specialization) can be used at this time. The display instantiation needs to be redefined. The format is:template<> TypeName function<typename> (argu_list) {...}; Template<> class classname<typename>{...};

Instantiation and materialization of C + + templates

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.