C++ offers a rich set of features and concepts for advanced programming. These
topics enable developers to write efficient, scalable, and maintainable code for
complex applications.
1. Templates
Templates provide a way to write generic and reusable code. They allow functions
and classes to work with any data type.
1.1 Function Templates
Function templates define a blueprint for functions that work with different data
types.
#include <iostream>
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
std::cout << add<int>(3, 4) << "\n"; // Output: 7
std::cout << add<double>(3.5, 4.5) << "\n"; // Output: 8
return 0;
}
1.2 Class Templates
Class templates generalize a class for any data type.
#include <iostream>
template <typename T>
class Box {
T value;
public:
, Box(T v) : value(v) {}
T getValue() { return value; }
};
int main() {
Box<int> intBox(10);
Box<std::string> strBox("Hello");
std::cout << intBox.getValue() << "\n"; // Output: 10
std::cout << strBox.getValue() << "\n"; // Output: Hello
return 0;
}
2. Smart Pointers
Smart pointers manage dynamic memory and ensure proper cleanup. They are
part of the <memory> header.
2.1 Types of Smart Pointers
1. std::unique_ptr: Allows only one owner of the object.
2. std::shared_ptr: Allows multiple shared owners of the object.
3. std::weak_ptr: Works with std::shared_ptr but does not increase the
reference count.
Example
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> sp = std::make_shared<int>(10);
std::cout << *sp << "\n"; // Output: 10
return 0;
}