Presentation 2
Presentation 2
• Group Members:
• Muhammad Tahir : university roll number 1301-241019
•
•
Introduction to Templates:
• 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:
•
Inheritance with templates:
• template <class T>
• class PrettyBox : public Box<T> { /*...*/ };
• STL Example:
•
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>
•constexpr T max_limit = numeric_limits<T>::max();
• Why Useful?:
• Replace #define macros with type-safe alternatives.
•
•
•
Non-Type Template Parameters:
What?:
Templates can accept values (not just types).
Example:
class Array {
private:
public:
Array<10> arr; // N = 10
Use Cases:
Compile-time computations (e.g., factorial).
Fixed-size containers (like std::array).
Template Metaprogramming:
• Compile-Time Power:
• struct Factorial {
• template <>
•
Best Practices & Pitfalls:
• Dos:
•
• Don’ts:
•
• Avoid overly complex template hierarchies.
• static_assert(is_integral<T>::value, "Must
be integer");
• cout << val;
•}
•
Real-World Applications:
• 1-STL Containers: vector<T>, map<K,V>.
•
• 2-Smart Pointers: unique_ptr<T>, shared_ptr<T>.
•
Summary & Q&A!
• Key Takeaways:
•
• Function Templates: Generic algorithms.
•
• Class Templates: Reusable data structures.
•
• Variable Templates: Type-safe constants.
•
Q&A :
• "What happens if you try to
instantiate Stack<Employee> without
defining operator>?"
•