What is the difference between templates and macros in C++?

PointTemplateMacro
Done byCompilerPreprocessor (text)
Type safeYesNo
Scope and namespacesYesNo
DebuggingNormalHard
Side effectsNoneArguments 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
C++ Templates and Generic Programming
C++ STL Containers: map, set, unordered_map, queue and stack
C++ Algorithms and Iterators
Exercises & Assignments
Write a generic maximum template
Count the frequency of words with a map
Remove duplicates from a vector and keep the order
Interview Questions & Answers
What is the STL in C++?
What is the difference between std::map and std::unordered_map?
What is the difference between push_back and emplace_back in C++?
What is iterator invalidation in C++?
What is the difference between templates and macros in C++?