- Templates Overview
- Function Templates
- Class Templates
- Template Parameter Types
- Exercise Implementations
Templates are a feature in C++ that allows writing code that can work with any data type. They provide:
- Generic programming capabilities
- Type-safe code reuse
- Compile-time polymorphism
- Template Parameters
- Template Instantiation
- Template Specialization
- Template Resolution
template<typename T>
T functionName(T parameter) {
// Function body
}-
Type Deduction
- Compiler automatically determines type
- Must be unambiguous
-
Explicit Specialization
template<> void function<int>(int x) { // Specialized implementation for int }
-
Function Overloading
- Templates can be overloaded
- Most specific version is chosen
- Keep templates in header files
- Use meaningful parameter names
- Document type requirements
- Handle edge cases
template<typename T>
class ClassName {
private:
T member;
public:
T getMember() const { return member; }
};-
Member Functions
- Can be defined inside or outside class
- Must include template parameters
-
Static Members
- Each instantiation has its own set
- Must be declared and defined
-
Template Parameters
- Can have default values
- Can be types or non-types
-
Construction
T* array = new T[size](); // Default initialization
-
Destruction
delete[] array; // Proper array cleanup
-
Copy Semantics
- Deep copy required for pointers
- Handle self-assignment
template<typename T, typename U>
T convert(U value);template<typename T, int Size>
class Array {
T data[Size];
};template<template<typename> class Container>
class Wrapper;Implementation of basic utility functions:
template<typename T>
void swap(T& a, T& b);
template<typename T>
const T& min(const T& a, const T& b);
template<typename T>
const T& max(const T& a, const T& b);Key Points:
- Work with any comparable type
- Return consistent values (second when equal)
- Maintain const correctness
A template function for array iteration:
template<typename T>
void iter(T* array, size_t length, void (*func)(T&));Features:
-
Generic Array Processing
- Works with any array type
- Supports any function type
- Handles const correctly
-
Function Application
- Applies function to each element
- Maintains type safety
- Supports function templates
Template array class implementation:
template<typename T>
class Array {
private:
T* elements;
unsigned int _size;
public:
// ... member functions
};