Templates
Write code once that works with many types — the basis of the STL.
Intermediate
template <typename T>
T clamp_value(T value, T low, T high) {
return value < low ? low : (value > high ? high : value);
}
clamp_value(150, 0, 100); // int
clamp_value(3.7, 0.0, 3.3); // double
template <typename T, std::size_t N>
class RingBuffer { T data_[N]; /* ... */ }; // size known at compile time
The compiler generates a separate version for each type used, so templates have no run-time cost — great for embedded buffers and drivers.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.