Difference between template and macro in C++
In this article, we will discuss the difference between template and macro in C++. But before discussing the differences, we must know about the template and macro with their examples.
What is the template?
A template in C++ is like a blueprint or a recipe that allows you to create functions or classes that can work with different data types without writing separate code for each type. It's a way to achieve code reusability and make your programs more flexible.
Suppose you want to create a function that finds the maximum of two numbers. You can use a template instead of writing a separate function for integers, doubles, and other types. The template defines a generic version of the function that works with any data type you want to use. When you call the function with specific values, the C++ compiler automatically generates a version of that function specialized for the data type you provided.
Example program for the function template:
#include<iostream>
using namespace std;
template<typename t1>
t1 Max_Function(t1 a, t1 b){
if(a>b){
return a;
}else{
return b;
}
}
int main(){
int a1=100,b1=200;
cout<<"largest element in above two integer values "<<Max_Function(a1,b1)<<endl;
float a2=10.10,b2=20.20;
cout<<"largest element in above two floating values "<<Max_Function(a2,b2)<<endl;
char a3='z',b3='y';
cout<<"largest element in above two characters "<<Max_Function(a3,b3)<<endl;
return 0;
}
Output:
![Difference between template and macro in C++](https://static.tutorialandexample.com/cpp/difference-between-template-and-macro-in-cpp1.png)
Explanation:
In this example, the given code defines a function template Max_Function that finds the maximum of two values of any data type t1. After that, it demonstrates the template's use to find the largest element among integers, floating-point numbers, and characters. The Max_Function template compares the two values and returns the larger one. The main function tests the template by calling it with different data types (int, float, and char) to find the maximum value and displays the results using cout. The output will show the largest elements among the given pairs of values for each data type.
Example program for the class template:
#include<iostream>
using namespace std;
template<class t1>
class triplet{
private:
t1 x;
t1 y;
t1 z;
public:
triplet(t1 a,t1 b,t1 c){
x=a;
y=b;
z=c;
}
void display(){
cout<<"The given values are "<<endl;
cout<<x<<" "<<y<<" "<<z<<" "<<endl;
}
};
int main(){
int x1=100,y1=200,z1=300;
float x2=10.9,y2=20.9,z2=30.9;
char x3='a',y3='b',z3='c';
triplet<int> obj1(x1,y1,z1);
obj1.display();
triplet<float> obj2(x2,y2,z2);
obj2.display();
triplet<char> obj3(x3,y3,z3);
obj3.display();
}
Output:
![Difference between template and macro in C++](https://static.tutorialandexample.com/cpp/difference-between-template-and-macro-in-cpp2.png)
Explanation:
In this example, the class template triplet holds three values of the same data type t1. It has a constructor to initialize the three values provided during object creation. After that, the display function prints the three values of the object. In the main() function, it creates obj1 with integers (100, 200, 300) and prints them. After that, it creates obj2 with floats (10.9, 20.9, 30.9) and prints them. It creates obj3 with characters ('a', 'b', 'c') and prints them. Finally, the output displays the given values for each object: integers, floats, and characters.
What is Macro?
Macro in C++ is a way to create a shortcut for a piece of code. It's like giving a name to a set of instructions so that whenever you use that name, the associated code gets inserted directly into your program. It happens before the actual compilation of your code starts.
Think of macros as a copy-paste mechanism. When you use a macro, the preprocessor takes the macro name and replaces it with the corresponding code defined in the macro. It's like a text replacement process. It can be useful for repetitive tasks or for writing compact code.
However, macros have some limitations. They don't understand the code context, and since it's a simple text replacement, it can sometimes lead to unexpected issues or errors. For this reason, using macros for complex tasks or where type safety is important is generally discouraged in favor of using C++ templates.
Example program 1 for the macro:
#include<iostream>
#define maxi(a, b) ((a) > (b) ? (a) : (b))
using namespace std;
int main(){
int num1=100,num2=200;
cout<<"Printing the maximum value"<<endl;
cout<<maxi(num1,num2);
}
Output:
![Difference between template and macro in C++](https://static.tutorialandexample.com/cpp/difference-between-template-and-macro-in-cpp3.png)
Explanation:
In this example, the program uses a macro to find the maximum value between two given numbers. It includes the necessary header files (iostream for input-output and vector, though it is not used in the code). The macro maxi(a, b) is defined, which takes two arguments, and it returns the greater of the two. In the main() function, it initializes two integer variables num1 and num2, with values 100 and 200, respectively. After that, the program prints the message "Printing the maximum value" and outputs the result of the macro maxi(num1, num2), which will be the larger of the two numbers (200 in this case) as a single output.
Example program 2 showing usage of macro:
#include<iostream>
#include<vector>
#define forloop(i,n) for(int i=0 ; i<n ; i++)
using namespace std;
int main(){
vector<int> v1;
int i;
// Filling values to the vector using macro
forloop(i,5) v1.push_back(i+1);
// printing the values using macro forloop which is already defined above
forloop(i,5) cout<<v1[i]<<" ";
}
Output:
![Difference between template and macro in C++](https://static.tutorialandexample.com/cpp/difference-between-template-and-macro-in-cpp4.png)
Explanation:
In this example, the code defines a macro forloop(i,n) that simplifies creating loops to iterate over a range of numbers. In the main() function, it declares a vector v1 to store integers and an integer variable i. After that, it uses the macro to fill the vector with values 1 to 5 (inclusive). The forloop(i,5) is expanded by the preprocessor as for (int i = 0; i< 5; i++), effectively creating a loop that iterates from 0 to 4. Similarly, it prints the values of the vector using the same macro in the loop. The output will be: "1 2 3 4 5".
The key difference between the Template and Macro:
![Difference between template and macro in C++](https://static.tutorialandexample.com/cpp/difference-between-template-and-macro-in-cpp5.png)
There are several key differences between the template and macro. Some main differences between the template and macro are as follows:
Field | Macros | Template | |||
Compilation | Macros are preprocessor directives. | Templates are Part of the compilation process. | |||
Code Replacement | Macros are just a simple text replacement. | Templates will generate specialized code at compile-time. | |||
scope | Macros have global scope. | Templates have normal scope rules. | |||
Debugging | In macros, debugging is difficult. | In templates, debugging is easy and also gives compiler errors. | |||
Code Readability | Macros lead to code obfuscation. | Templates enhance code readability. | |||
Preprocessor Limitations | Macros have no access to C++ constructs. | Templates can use all C++ constructs and features. | |||
Function/Class Overload | Macros will not support. | Templates will support function/class overloading. | |||
Template Arguments | For macros not applicable. | Templates contain Type and non-type template parameters. | |||
Namespaces | Macros do not, potentially causing name clashes and unintended side effects. | Templates respect namespaces, ensuring proper encapsulation of code. | |||
Code Safety | Macros can inadvertently alter code semantics and introduce bugs. | Templates ensure type safety, preventing unintended side effects and promoting cleaner code. | |||
Functionality Expansion | Macros are limited in their ability to add new functionality. | Templates can expand functionality through function and class overloading, adapting to different data types. | |||
Conclusion:
In conclusion, templates and macros are both useful tools for code reuse and flexibility, but they are fundamentally different. Templates are a compile-time mechanism for generic programming, enabling the creation of reusable code that works with various data types, while macros are a preprocessor feature that performs textual replacement, allowing for more direct manipulation of the code. It's essential to choose the right tool for the specific task to write maintainable, efficient, and bug-free code.