Presentation 2
Presentation 2
• What?:
Why?:
• Avoid code duplication (write once, use for any type).
T add(T a, T b) { return a + b;
Key concepts;
1-Template Instantiation:
• Template Specialization
template <>
}
• Basic Syntax:
Class Templates:
• template <class T>
• class Box {
• private:
• T content;
• public:
•
Variable Templates :
• Core Idea:
• Typed constants or compile-time values.
• Examples:
• 1-Mathematical Constants:
• template <typename T>
• constexpr T pi = T(3.141592653589793);
• cout << pi<double>; // High precision
• 2-Type-Dependent Values:
• template <class T>
•
Non-Type Template Parameters:
What?:
Templates can accept values (not just types).
Example:
class Array {
private:
public:
Array<10> arr; // N = 10
Use Cases:
• struct Factorial {
• };
• template <>
• Don’ts:
• static_assert(is_integral<T>::value, "Must be
integer");
• cout << val;
•}
Real-World Applications:
• 1-STL Containers: vector<T>, map<K,V>.