What are templates ? Templates allow us to write one function or class that works for different data types. Using templates we can write a single class or function for many data types. Example: type safe collection class like stack, queue etc that can handle data of any type.
Function Template: When we write any function with template then its called as Function template.
Class Template: When we write any class with template then its called as Class template.
Function Template example and Source code:
//Header File #include<iostream> //Function Template template <typename T > T AddNumber(T a, T b) { return(a+b); }; //client int main() { std::cout<<"Function Template"<<std::endl; int i_res = AddNumber<int>(2, 2); float f_res = AddNumber<float>(2.2, 2.2); std::cout<<"Int Result:"<<i_res<<std::endl; std::cout<<"Float Result:"<<f_res<<std::endl; return 0; }