Template cho phép viết code generic — hoạt động với nhiều kiểu mà không cần copy-paste. Compiler tạo bản cụ thể (instantiation) khi cần.
Function template:
template <typename T>
T max_val(T a, T b) { return a > b ? a : b; }
max_val(3, 5); // T = int
max_val(3.0, 5.0); // T = doubleClass template:
template <typename T>
class Stack {
std::vector<T> data_;
public:
void push(T val) { data_.push_back(val); }
T pop() { T v = data_.back(); data_.pop_back(); return v; }
};
Stack<int> si;
Stack<std::string> ss;Template specialization: định nghĩa cài đặt riêng cho kiểu cụ thể — ví dụ template <> max_val<int>(...) dùng SIMD.
STL hoàn toàn được xây dựng trên template — đây là lý do std::vector<int> và std::vector<double> cùng API.
Templates allow writing generic code that works across multiple types without copy-pasting. The compiler generates concrete instantiations on demand.
Function template:
template <typename T>
T max_val(T a, T b) { return a > b ? a : b; }
max_val(3, 5); // T = int
max_val(3.0, 5.0); // T = doubleClass template:
template <typename T>
class Stack {
std::vector<T> data_;
public:
void push(T val) { data_.push_back(val); }
T pop() { T v = data_.back(); data_.pop_back(); return v; }
};
Stack<int> si;
Stack<std::string> ss;Template specialization: custom implementation for a specific type — e.g. template <> max_val<int>(...) using SIMD.
The entire STL is built on templates — which is why std::vector<int> and std::vector<double> share the same API.