Lesson 3 of 7
Inventory Template & FileStore
The `Inventory<T>` template manages a collection of `unique_ptr<T>` with O(1) ID lookup and O(log n) category lookup. It provides a complete, type-safe CRUD API. The `FileStore` handles CSV persistence with strong exception safety - it writes to a temporary file and renames atomically, so the inventory file is never left in a corrupt state.
Inventory<T> Template & FileStore - CRUD + Persistence
// โโ include/inventory.h โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
#pragma once
#include <vector>
#include <memory>
#include <unordered_map>
#include <map>
#include <optional>
#include <algorithm>
#include <functional>
#include <string_view>
#include "exceptions.h"
template<typename T>
class Inventory {
std::vector<std::unique_ptr<T>> items_; // owns all items
std::unordered_map<int, T*> id_index_; // O(1) id lookup
std::map<std::string, std::vector<int>> cat_index_; // sorted categories
public:
Inventory() = default;
// Rule of 0: unique_ptr handles memory; auto-movable
// โโ CRUD โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
T& add(std::unique_ptr<T> item) {
T* raw = item.get();
int id = raw->id();
if (id_index_.count(id)) throw InventoryError("Duplicate id: " + std::to_string(id));
id_index_[id] = raw;
cat_index_[raw->category()].push_back(id);
items_.push_back(std::move(item));
return *raw;
}
T& find(int id) {
auto it = id_index_.find(id);
if (it == id_index_.end()) throw ProductNotFound(id);
return *it->second;
}
const T& find(int id) const {
auto it = id_index_.find(id);
if (it == id_index_.end()) throw ProductNotFound(id);
return *it->second;
}
std::optional<T*> try_find(int id) {
auto it = id_index_.find(id);
if (it == id_index_.end()) return std::nullopt;
return it->second;
}
bool remove(int id) {
auto id_it = id_index_.find(id);
if (id_it == id_index_.end()) return false;
T* raw = id_it->second;
// Remove from category index
auto& cat_ids = cat_index_[raw->category()];
cat_ids.erase(std::remove(cat_ids.begin(), cat_ids.end(), id), cat_ids.end());
if (cat_ids.empty()) cat_index_.erase(raw->category());
// Remove from id index
id_index_.erase(id_it);
// Remove from main storage
items_.erase(std::remove_if(items_.begin(), items_.end(),
[id](const auto& p){ return p->id() == id; }),
items_.end());
return true;
}
// โโ Query API - lambdas โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
template<typename Pred>
std::vector<T*> filter(Pred pred) const {
std::vector<T*> result;
for (const auto& p : items_) {
if (pred(*p)) result.push_back(p.get());
}
return result;
}
std::vector<T*> by_category(std::string_view cat) const {
std::vector<T*> result;
auto it = cat_index_.find(std::string(cat));
if (it == cat_index_.end()) return result;
for (int id : it->second) {
auto id_it = id_index_.find(id);
if (id_it != id_index_.end()) result.push_back(id_it->second);
}
return result;
}
template<typename Compare = std::less<>>
std::vector<T*> sorted(Compare cmp = {}) const {
std::vector<T*> result;
std::transform(items_.begin(), items_.end(),
std::back_inserter(result),
[](const auto& p){ return p.get(); });
std::sort(result.begin(), result.end(),
[&cmp](const T* a, const T* b){ return cmp(*a, *b); });
return result;
}
// โโ Aggregation โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
size_t count() const noexcept { return items_.size(); }
double total_value() const noexcept {
double t = 0;
for (const auto& p : items_) t += p->price() * p->quantity();
return t;
}
std::vector<std::string> categories() const {
std::vector<std::string> c;
for (const auto& [cat, _] : cat_index_) c.push_back(cat);
return c;
}
// โโ For range-based for โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
auto begin() const { return items_.cbegin(); }
auto end() const { return items_.cend(); }
};
// โโ Simplified FileStore snippet โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Full implementation in src/filestore.cpp
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
class FileStore {
fs::path data_dir_;
fs::path csv_path_;
public:
explicit FileStore(fs::path dir)
: data_dir_(std::move(dir))
, csv_path_(data_dir_ / "inventory.csv")
{
fs::create_directories(data_dir_);
}
// Strong exception guarantee: write to temp then rename atomically
void save(const Inventory<Product>& inv) {
fs::path tmp = csv_path_.string() + ".tmp";
try {
std::ofstream f(tmp);
if (!f) throw PersistenceError("Cannot write: " + tmp.string());
f << "id,name,category,price,quantity,extra
";
for (const auto& p : inv) {
f << p->serialize() << "
";
if (!f) throw PersistenceError("Write error during save");
}
f.close();
fs::rename(tmp, csv_path_); // atomic rename - strong guarantee
} catch (...) {
if (fs::exists(tmp)) fs::remove(tmp); // cleanup temp
throw; // rethrow for caller
}
}
};Design Decisions
- **Atomic save with rename** - writing to `.tmp` then renaming means the main CSV is never in a partial state. If power fails mid-write, the `.tmp` file contains the corrupt partial write, and the original `.csv` is untouched. This implements the strong exception guarantee for persistence.
- **Raw pointer observer in index** - `unordered_map<int, T*>` stores raw (non-owning) pointers. This is acceptable here because the `items_` vector holds the `unique_ptr` owners, and the index's lifetime is bounded to the `Inventory` object. Raw pointers for observation within a well-defined lifetime scope are valid modern C++.
- **`try_find` returning `optional<T*>`** - returning `optional<T*>` instead of `T*` (nullable) makes the 'not found' case explicit in the type system. Callers cannot forget to null-check because they must call `.value()` or check the optional first.
Tip
Tip
Practice Inventory Template FileStore in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
In-Memory Fast O(1) Lookup Cache Coupled with RAII Transactional Disk Persistence
Practice Task
Note
Practice Task - (1) Write a working example of Inventory Template FileStore from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Inventory Template FileStore is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- The `Inventory<T>` template manages a collection of `unique_ptr<T>` with O(1) ID lookup and O(log n) category lookup.
- *Atomic save with rename** - writing to `.tmp` then renaming means the main CSV is never in a partial state. If power fails mid-write, the `.tmp` file contains the corrupt partial write, and the original `.csv` is untouched. This implements the strong exception guarantee for persistence.
- *Raw pointer observer in index** - `unordered_map<int, T*>` stores raw (non-owning) pointers. This is acceptable here because the `items_` vector holds the `unique_ptr` owners, and the index's lifetime is bounded to the `Inventory` object. Raw pointers for observation within a well-defined lifetime scope are valid modern C++.
- *`try_find` returning `optional<T*>`** - returning `optional<T*>` instead of `T*` (nullable) makes the 'not found' case explicit in the type system. Callers cannot forget to null-check because they must call `.value()` or check the optional first.
Finished this lesson?