TEMPLATES in C++

Photo by Joan Gamell on Unsplash

TEMPLATES in C++

What are Templates?

Templates are the function of C++ that allows us to write generic code. With the help of Templates, we can write our own functions and classes and one of the best features of Templates is 'variable datatype' by using templates we don't need to write the same code for different datatypes.

Advantages of Templates:-

  • Code reusability, we don't have to write the same code to perform the same function instead Templates do the work for us.

  • Efficiency, many STL libraries and algorithms use templates to work efficiently.

Types of Templates:-

  • Function Templates: These are used to define a group of functions that can work with different datatypes.

Basic Syntax:

template <class T>
T myFunction(T arg) {
  // function body
}
  • Class Templates: These are used to define a family of classes that can work with different datatypes.

    Basic Syntax:

      template <class T>
      class myClass {
        public:
          T element;
          myClass (T arg) {element=arg;}
          T increase () {return ++element;}
      };
    

Click on this LINK to know more about templates it contains some examples and a short description this article will be expanded on in the future.