Templates in C++
-
What are Templates
Templates are blueprints for creating functions and classes. While using a template in C++, you pass a data type as a parameter. Thus, instead of maintaining multiple codes, you have to write one code and give the data type you want to use. For example you are creating print function and you will need to take any datatype as parameter. Instead of creating many function overloads, we can create a template that will be compiled into function overload according to datatype.
-
How to write template
You write template using
template
keyword in front of the function or class and then in<>
you write your template argument.typename
keyword allows you to put any datatype to template argument.template<typename T> void Print(T value){ std::cout << value << std::endl; }
and you use template function just like normal function but you specify template argument in
<>
template<typename T> void Print(T value){ std::cout << value << std::endl; } Print<int>(5);
Generated code from this template would look like this:
void Print( int value){ std::cout << value << std::endl; } Print(5);
You can also make templates with not only typename as argument and with classes.
template<int size> class Array{ private: int m_Array[size]; // size will be replaced by 5 public: int getSize() const { return size; } }; Array<5> arr;
Generated code from this template would look like this:
class Array{ private: int m_Array[5]; public: int getSize() const { return 5; } }; Array arr;