Templates in C++

Templates in C++

Standard Template Libraries in C++

  • STL is Standard Template Library.
  • It is a powerful set of C++ template classes.
  • At the core of C++ Standard Template Library are following three well-structured components.
    • Containers
    • Algorithms
    • Iterators

Ohh! have I gotten far ahead from the topic, Sumimasen!

Coming straight back to the topic, Here is all about templates in C++.

Templates in C++ Language

The keyword template is used to define function templates and class templates in our C++ program. It introduces generic programming, which makes a way for programmers to write more efficient code.

So, now there are two ways in which we can use template,

  • Function template

    Function template is also known as generic function.

syntax creating function template:

template<class type> 
type func_name(type arg1, type arg2, ....){
     ...
};
// here type is a placeholder for generalisation of data type.

It creates a function template named func_name with any number of arguments.

आइए इसे एक उदाहरण से समझते हैं,

Program to find the smaller number from the given two numbers without the use of template:

To avoid using different data types in a function, Use template.

Example 2:

  • Class template

    Class template is also known as generic class.
template<class type> 
class class_name{
    ...
};
// here type is also a placeholder to generalise a class.

It creates a class template named class_name.

Let's also learn this with an example, Here we are making a arrayList class without the use of template.

Image explanation of code.

template_c++.png

Now, templating our above program will result in increased possibilities of input with the same number of lines of code.

visit : arrayList_with_template.cpp

So, Here we come again, starting with STL, Standard Template Libraries.

  • STL is Standard Template Library.
  • It is a powerful set of C++ template classes.
  • At the core of C++ Standard Template Library are following three well-structured components.
    • Containers
    • Algorithms
    • Iterators

STL will be covered in upcoming nodes. :)

stay tuned...