Template in C ++

The template is the foundation of generic programming, ie code according to which is independent of any specific type.

A Template is a blueprint or method to create a class or a general function. Container libraries like iterators and algorithms are examples of general programming and have been developed using the concept of Template.

Each container has a single definition, vector example, but we can define many different vector series, for example: vector or vector .

Template is a keyword in C ++, we can understand that it is an abstract data type, specific to the basic data types. A template is a keyword that tells the compiler that the following code defines multiple data types and that its source code will be compiled to correspond to each data type during compilation. There are two types of templates in C ++:

Function Template: is a function template that allows you to define general functions for multiple data types.

Class template: is a class template that allows to define general classes for many data types

Function Template in C ++

Here is the general syntax of a Function Template definition in C ++:

 template < class kieu_du_lieu > kieu_tham_chieu ten_ham ( danh sach tham so ) { // phan than ham } 

Here, kieu_du_lieu is a name of a data type used by the function. This name can be used within the function definition.

The following is an example of Function Template that returns the maximum value of two values:

 #include #include using namespace std ; template < typename QTM > inline QTM const & Max ( QTM const & a , QTM const & b ) { return a < b ? b : a ; } int main () { int i = 15 ; int j = 26 ; cout << "Gia tri lon nhat cua (i, j) la: " << Max ( i , j ) << endl ; double f1 = 4.5 ; double f2 = 14.2 ; cout << "Gia tri lon nhat cua (f1, f2) la: " << Max ( f1 , f2 ) << endl ; string s1 = "HocLapTrinhCplusplus" ; string s2 = "TaiQTM" ; cout << "Gia tri lon nhat cua (s1, s2) la: " << Max ( s1 , s2 ) << endl ; return 0 ; } 

At the template line, if you use the class instead of typename as in the syntax, the program still runs normally. Because with the class and typename defined in C ++. As for other names, like tenKieuCuaToi , it won't run !!

Compile and run the above C ++ program to see the results:

Class Template in C ++

Just like when we can define Function Template, we can also define the Class Template in C ++. The general syntax of defining a Class Template in C ++ is:

 template < class kieu_du_lieu > class ten_lop { . . . } 

Here, kieu_du_lieu is the type name, which will be determined when a class is declared. You can define more than one generic data type by using a list separated by commas.

The following example defines the Stack class and implements general methods to push and pop elements from that Stack. (Stack: stack, push: add a new node to the top of the stack, pop: operation takes 1 element from the stack top).

 #include #include #include #include #include using namespace std ; template < class QTM > class Stack { private : vector < QTM > phantu ; // cac phan tu public : void push ( QTM const &); // hoat dong push phan tu void pop (); // hoat dong pop phan tu QTM top () const ; // tra ve phan tu tren cung bool empty () const { // tra ve true neu la trong. return phantu . empty (); } }; template < class QTM > void Stack < QTM >:: push ( QTM const & elem ) { // phu them ban sao cua phan tu da truyen phantu . push_back ( elem ); } template < class QTM > void Stack < QTM >:: pop () { if ( phantu . empty ()) { throw out_of_range ( "Stack<>::pop(): stack da trong!" ); } // xoa phan tu cuoi cung phantu . pop_back (); } template < class QTM > QTM Stack < QTM >:: top () const { if ( phantu . empty ()) { throw out_of_range ( "Stack<>::top(): stack da trong!" ); } // tra ve ban sao cua phan tu cuoi cung return phantu . back (); } int main () { try { Stack stackSoNguyen ; // mot stack cua cac so nguyen Stack stackChuoi ; // mot stack cua cac chuoi // thao tac tren stack cac so nguyen stackSoNguyen . push ( 10 ); cout << stackSoNguyen . top () << endl ; // thao tac tren stack cua chuoi stackChuoi . push ( "QTMXinChaoCacBan" ); cout << stackChuoi . top () << std :: endl ; stackChuoi . pop (); stackChuoi . pop (); } catch ( exception const & ex ) { cerr << "Exception: " << ex . what () << endl ; return - 1 ; } } 

In the above program, the out_of_range exception is already defined in C ++. Compile and run the above C ++ program to see the results:

According to Tutorialspoint

Previous article: Namespace in C ++

Next article: Preprocessor in C ++

4 ★ | 1 Vote

May be interested

  • 9 great websites to download mockup templates for design9 great websites to download mockup templates for design
    the mockup sites on this list are for all kinds of designs, such as t-shirts, devices, billboards, and anything else you can imagine your logo or design will be used on.
  • How to use OneNote templateHow to use OneNote template
    onenote 2016 has a lot of page templates. they provide you with built-in layouts with a variety of formatting options, helping you create clear and structured notes accordingly.
  • How to create a master template for presentations in FigmaHow to create a master template for presentations in Figma
    if you're creating a stylized presentation, but don't want to use the familiar templates from powerpoint, google slides, or canva, you can create your own master template for future presentation designs.
  • How to Use Function Template Parameter Packs in C++How to Use Function Template Parameter Packs in C++
    c++ template parameter packs (also known as variadic templates) were introduced in the c++11 standard and are powerful tools that let functions accept an arbitrary number of arguments. without further ado, jump into your favourite ide,...
  • How to create a Template template in Word 2007 and Word 2010How to create a Template template in Word 2007 and Word 2010
    microsoft word supports users with a series of useful features, making the work of writing documents and documents faster and simpler. with these formats, operations ... often have to be used repeatedly in word instead of having to re-type a series of addresses
  • 5 free HTML templates for creating web pages quickly5 free HTML templates for creating web pages quickly
    the following suggestions are simple templates that you can adjust to your own needs, to create a simple website. the template comes with instructions for you to use them even if you are a beginner to html.
  • Create a quick website with HTML5 BoilerplateCreate a quick website with HTML5 Boilerplate
    when building a new website, you need that website compatible with html5 but don't want to take the time to learn the complicated knowledge about html5 from the beginning, you can use the html5 boilerplate template. this is a simple front-end template for creating an html5 website in minutes.
  • How to fix hidden templates in Google DocsHow to fix hidden templates in Google Docs
    you can also create your own templates and upload them to the template gallery. however, sometimes it may happen that the templates are hidden in docs, sheets, from which you cannot select the content template.
  • Download the most beautiful Slide PowerPoint template 2021Download the most beautiful Slide PowerPoint template 2021
    collection of beautiful slides. if you have not found a beautiful powerpoint slide design template, please refer to the following article.
  • How to create a template for PowerPoint presentation slidesHow to create a template for PowerPoint presentation slides
    often the process of making slides you often use the template available. but in some cases you want to be unique from everyone by creating your own presentation templates. the following article helps you create your own template in powerpoint.