Difference between Preprocessor Directives and Function Templates in C++
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:
C++
// C++ program to illustrate// preprocessor directives#include <bits/stdc++.h> #define min(a, b) ((a < b) ? a : b) using namespace std; // Driver codeint main(){ int a = 2, b = 4; // Find the minimum of a and b cout << "Minimum of both is: " << min(a, b); return 0;} |
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:
C++
// C++ program to illustrate the use// of Function Templates#include <iostream>#include <stdio.h>using namespace std; // Function Templatetemplate <class T>T Min(T x, T y){ return (x < y) ? x : y;} // Driver Codeint main(){ int a = 4, b = 8; // Find the minimum of a and b cout << "Minimum of both is: " << min(a, b); return 0;} |
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 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:
- In the case of Pre-processor directives, there is no type checking. But in the case of templates, full type checking is done by the compiler.
- Pre-processor directives can call an unexpected result. Consider a macro that calculates the square of any number as:
#define sqr(x) (x*x)
- Now if this macro is called using the following statement, x = sqr(4 + 4); then expected output is 64 but it generates 24 because any x in macro body replaced by 4 + 4 which leads to x = 4 + 4 * 4 + 4 = 24 but in the case of templates, such unexpected results are not obtained.
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 preprocessed They are compiled 3 They can work with any data type They are used with #define preprocessor directives 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 have explicit full specialization They don’t have explicit full specialization


