C++ Templates

C++ <Templates>

In This Article, you'll learn about templates / Generic templates in C++ how and how effective is Template in  Cpp programming.

Templates are another Powerfull feature of C++.T hats allow User to write a generic Function / Class or single generic Function/class and implement that class or function with Different Variables/Data Types using Templates. or we can also say C++ templates The simple idea is to pass data type as Parameter so that we don't need to write the same code multiple-times for different data types.
Templates often used in Large length of codes.
Example:  we need count() for counting numbers, Characters, String, words Etc.without using Templates user need to define count() for each separate. but with C++ Template we can define count() method as Template Method.. the all we need to just Pass different args(argument/parameter) as per requirement.

  • Function Templates
 Function Templates is similar to Normal Function But with Different Prefix.
Difference Between Function Templates &Function. A single Function Templates can be used with Different data types.
A regular function only works with single data types.

How to Define Function Templates.
#include "iostream"
      using namespace std;

template <class T>
T FindMax (T a, T b) {
  T result;
  result = (a>b)? a : b;
  return (result);
}
Full Example here

In above Program we declare Template function with Prefix template(keyword). and followed by
templates parameters inside <> which followed by Function declaration.In above code T is an 
template function argument that accepts different Data types (int,float,etc) and class is keyword here
We can also use typename instead of a class keyword.
when, an  argument of a data type is passed to someFunction(),compiler generates a new version
of someFunction() for the given Data type.
 

Comments