What is the difference between templates and macros in C++?
| Point | Template | Macro |
|---|---|---|
| Done by | Compiler | Preprocessor (text) |
| Type safe | Yes | No |
| Scope and namespaces | Yes | No |
| Debugging | Normal | Hard |
| Side effects | None | Arguments can be evaluated twice |
#include <iostream>
#define SQUARE(x) x * x
template <typename T>
constexpr T square(T x) { return x * x; }
int main() {
int n = 3;
std::cout << SQUARE(n + 1) << '\n'; // becomes n + 1 * n + 1 = 7: a macro bug
std::cout << square(n + 1) << '\n'; // 16: correct
}
Output
7
16
Use constexpr, const, templates and inline functions instead of macros. Macros stay useful for include guards and conditional compiling. See Templates.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |