![]() |
VOOZH | about |
Preprocessor Directives are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C / C++.
Below is the program to illustrate the functionality of Function Templates:
Minimum of both is: 2
Function Templates are the generic function that can handle different data types without the need for any separate code.
Below is the program to illustrate the functionality of Function Templates:
Minimum of both is: 4
Function templates are used to make generic functions that can work with any data type. For example, the function template used for calculating the minimum of 2 values of any type can be defined as:
template <class T>
T minimum(T a, T b)
{
return (a < b) ? a : b;
}
But, this task can also be performed using Pre-processor directives created using preprocessor directive #define. So, the minimum of the two numbers can be defined as:
#define minimum(a, b) ((a < b) ? a : b)
The Pre-processor directives can also be achieved by using the below statements:
minimum(30, 35);
minimum(30.5, 40.5);
In C++, most of us prefer using templates over Pre-processor directives because:
#define sqr(x) (x*x)
Below is the tabular difference between the two:
| S. No. | Pre-processor directives | Function Templates |
| 1 | There is no type checking. | There is full type checking. |
| 2 | They are pre-processed. | They are compiled. |
| 3 | They are used with #define preprocessor directives. | They can work with any data type. |
| 4 | They can cause an unexpected result. | No such unexpected results are obtained. |
| 5 | They don't ensure type safety in instance. | They do ensure type safety. |
| 6 | They don't have explicit full specialization. | They have explicit full specialization. |