The Wayback Machine - https://web.archive.org/web/20241001224037/https://www.geeksforgeeks.org/difference-between-preprocessor-directives-and-function-templates-in-c/
Open In App

Difference between Preprocessor Directives and Function Templates in C++

Last Updated : 26 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 code
int main()
{
    int a = 2, b = 4;

    // Find the minimum of a and b
    cout << "Minimum of both is: "
         << min(a, b);

    return 0;
}

Output
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 Template
template <class T>
T Min(T x, T y)
{
    return (x < y) ? x : y;
}

// Driver Code
int main()
{
    int a = 4, b = 8;

    // Find the minimum of a and b
    cout << "Minimum of both is: " << min(a, b);

    return 0;
}

Output
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:

  • 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 directivesFunction Templates
1There is no type checking.There is full type checking.
2They are pre-processed.They are compiled.
3They are used with #define preprocessor directives.They can work with any data type.
4They can cause an unexpected result.No such unexpected results are obtained.
5They don’t ensure type safety in instance.They do ensure type safety.
6They don’t have explicit full specialization.They have explicit full specialization.

Previous Article
Next Article

Similar Reads

C++ Preprocessor And Preprocessor Directives
The preprocessor in C++ is used for processing the code before it is compiled by the compiler. It does many tasks such as including files, conditional compilation, using macros, etc. The preprocessor also allows the developers to select which portions of code should be included or excluded. The code processed by the preprocessor is called expanded
7 min read
C Preprocessor Directives
In almost every C program we come across, we see a few lines at the top of the program preceded by a hash (#) sign. They are called preprocessor directives and are preprocessed by the preprocessor before actual compilation begins. The end of these lines is identified by the newline character '\n', no semicolon ';' is needed to terminate these lines
8 min read
Convert C/C++ program to Preprocessor code
We use g++ compiler to turn provided Cpp code into preprocessor code. To see the preprocessor code generated by the CPP compiler, we can use the “-E” option on the command line: Preprocessor include all the # directives in the code. and also expands MACRO function. Syntax: g++ -E filename.cpp // MACRO named MAX initialism to 10 #define MAX 10 int m
1 min read
Preprocessor output of cpp file
Preprocessing is a stage where preprocessor directives are expanded or processed before source code is sent to the compiler. The most common example of such directive is #include or #define. A preprocessor output has ".i" extension. Two files are created here: C/C++ Code // C++ program for the test.cpp #include "MyHeader.h" #include <i
3 min read
Function Overloading vs Function Templates in C++
In C++, both function overloading and function templates allow us to create functions that can operate on different types of data. While they might seem similar, they are used for different purposes. In this article, we will learn the differences between function overloading and function templates, and understand when to use each. Table of Content
4 min read
Difference between JSX vs Templates
JSX and Templates are two different things that are used by Javascript frameworks and libraries to show any content via DOM(Document Object Model). Nowadays there is a debate about using frameworks or libraries with JSX like ReactJs vs frameworks or libraries with Templates like VueJS. So there is a need to understand JSX and Templates. When you wi
5 min read
not1 and not2 function templates in C++ STL with Examples
These are functions which takes unary and binary function object(functors) and returns complement of that function objects. It can be usable in competitive programming to get complement of binary and unary functions. These functions are very useful when writing code for complement function is harder or lengthy. For example, if we want to delete con
3 min read
Overloading function templates in C++
Template: A template is a tool that reduces the efforts in writing the same code as templates can be used at those places.A template function can be overloaded either by a non-template function or using an ordinary function template. Function Overloading: In function overloading, the function may have the same definition, but with different argumen
3 min read
Abbreviated Function Templates in C++ 20
Abbreviated Function Template is a new feature introduced in C++20 to simplify the syntax of function template definition. Traditionally, we use function templates to define a function that can take parameters of different types. But sometimes, it might get complicated and hard to understand. In these cases, we can implement an abbreviated function
3 min read
Variadic function templates in C++
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue. Douglas Gregor and Jaakko Järvi came up with this feature for C+
3 min read
Templates and Static variables in C++
Function templates and static variables: Each instantiation of function template has its own copy of local static variables. For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist. #include <iostream> using namespace std; template <typename T> void fu
2 min read
Templates and Default Arguments
Default parameters for templates in C++: Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char. #include<iostream> using namespace std; template<class T, class U = char> class A { public: T x; U y; }; int main() { A<char
1 min read
C++ | Templates | Question 1
Which of the following is true about templates. 1) Template is a feature of C++ that allows us to write one code for different data types. 2) We can write one function that can be used for all data types including user defined types. Like sort(), max(), min(), ..etc. 3) We can write one class or struct that can be used for all data types including
1 min read
C++ | Templates | Question 2
Predict the output? #include <iostream> using namespace std; template <typename T> void fun(const T&x) { static int count = 0; cout << "x = " << x << " count = " << count << endl; ++count; return; } int main() { fun<int> (1); cout << endl; fun<int>(1); cout <<
1 min read
C++ | Templates | Question 3
#include <iostream> using namespace std; template <typename T> T max(T x, T y) { return (x > y)? x : y; } int main() { cout << max(3, 7) << std::endl; cout << max(3.0, 7.0) << std::endl; cout << max(3, 7.0) << std::endl; return 0; } (A) 7 7.0 7.0 (B) Compiler Error in all cout statements as data ty
1 min read
C++ | Templates | Question 4
Output of following program? #include <iostream> using namespace std; template <class T> class Test { private: T val; public: static int count; Test() { count++; } }; template<class T> int Test<T>::count = 0; int main() { Test<int> a; Test<int> b; Test<double> c; cout << Test<int>::count <
1 min read
C++ | Templates | Question 5
Output of following program? Assume that the size of char is 1 byte and size of int is 4 bytes, and there is no alignment done by the compiler. #include<iostream> #include<stdlib.h> using namespace std; template<class T, class U> class A { T x; U y; static int count; }; int main() { A<char, char> a; A<int, int> b; cout
1 min read
C++ | Templates | Question 6
Output of following program? Assume that the size of int is 4 bytes and size of double is 8 bytes, and there is no alignment done by the compiler. #include<iostream> #include<stdlib.h> using namespace std; template<class T, class U, class V=double> class A { T x; U y; V z; static int count; }; int main() { A<int, int> a; A
1 min read
C++ | Templates | Question 10
Output of following program. #include <iostream> using namespace std; template <class T, int max> int arrMin(T arr[], int n) { int m = max; for (int i = 0; i < n; i++) if (arr[i] < m) m = arr[i]; return m; } int main() { int arr1[] = {10, 20, 15, 12}; int n1 = sizeof(arr1)/sizeof(arr1[0]); char arr2[] = {1, 2, 3}; int n2 = sizeof(
2 min read
C++ | Templates | Question 8
Output? #include <iostream> using namespace std; template <int i> void fun() { i = 20; cout << i; } int main() { fun<10>(); return 0; } (A) 10 (B) 20 (C) Compiler Error Answer: (C) Explanation: Compiler error in line "i = 20;" Non-type parameters must be const, so they cannot be modified.Quiz of this Question
1 min read
C++ | Templates | Question 9
Output? #include <iostream> using namespace std; template <class T> T max (T &a, T &b) { return (a > b)? a : b; } template <> int max <int> (int &a, int &b) { cout << "Called "; return (a > b)? a : b; } int main () { int a = 10, b = 20; cout << max <int> (a, b); } (A) 20 (B)
1 min read
C++ | Templates | Question 10
Output? #include <iostream> using namespace std; template<int n> struct funStruct { static const int val = 2*funStruct<n-1>::val; }; template<> struct funStruct<0> { static const int val = 1 ; }; int main() { cout << funStruct<10>::val << endl; return 0; } (A) Compiler Error (B) 1024 (C) 2 (D) 1 Answe
1 min read
Implementing Stack Using Class Templates in C++
The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). The simple idea is to pa
5 min read
C++ Variable Templates
Over the years C++ has undergone advancements to improve its capabilities and coding efficiency. One notable addition in C++14 is the introduction of variable templates. These variable templates allow you to create a group of variables or static data members that can be customized providing flexibility for your code. Variable TemplatesVariable temp
4 min read
Why can templates only be implemented in the header file?
Templates are a powerful feature in C++ that allows for the creation of generic functions and classes. They provide a way to write code that works with different data types without sacrificing type safety. However, one notable restriction when working with templates is that their implementation is often required to be in the header file. This limit
4 min read
Templates in C++ vs Generics in Java
While building large-scale projects, we need the code to be compatible with any kind of data which is provided to it. That is the place where your written code stands above that of others. Here what we meant is to make the code you write be generic to any kind of data provided to the program regardless of its data type. This is where Generics in Ja
4 min read
Vue Templates
Vue.js is a progressive JavaScript framework for building user interfaces. One of the core features of Vue.js is its templating system, which allows developers to declaratively bind data to the DOM. In this article, we will explore the basics of Vue templates, including syntax, directives, binding, conditional rendering, loops, and best practices.
2 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Difference between user defined function and library function in C/C++
Library Functions These functions are the built-in functions i.e., they are predefined in the library of the C. These are used to perform the most common operations like calculations, updation, etc. Some of the library functions are printf, scanf, sqrt, etc. To use these functions in the program the user has to use a header file associated with the
3 min read
Difference between virtual function and inline function in C++
Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th
2 min read
Practice Tags :