Lesson 5 of 6
Mini Project Part 7 - Generic Stack Template
Build a production-ready generic `Stack<T>` with full specialisation for `Stack<std::string>` (JSON-safe serialisation), partial specialisation `Stack<T*>` (pointer semantics), and a variadic `make_stack(args...)` factory. Everything from this module in one project.
Generic Stack - Specialisations & Variadic Factory
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <utility>
#include <sstream>
// ── Primary Stack template ────────────────────────────────────
template<typename T>
class Stack {
protected:
std::vector<T> data_;
public:
Stack() = default;
void push(T val) { data_.push_back(std::move(val)); }
T pop_top() { auto v=std::move(data_.back()); data_.pop_back(); return v; }
T& top() { if (empty()) throw std::out_of_range("empty"); return data_.back(); }
bool empty() const { return data_.empty(); }
size_t size() const { return data_.size(); }
std::string serialize() const {
std::ostringstream oss;
oss << "[";
for (size_t i=0; i<data_.size(); ++i) {
if (i) oss << ",";
oss << data_[i];
}
oss << "]";
return oss.str();
}
friend std::ostream& operator<<(std::ostream& os, const Stack& s) {
return os << s.serialize();
}
};
// ── Full specialisation for string - JSON-quoted ──────────────
template<>
class Stack<std::string> {
std::vector<std::string> data_;
public:
void push(std::string val) { data_.push_back(std::move(val)); }
std::string pop_top() { auto v=std::move(data_.back()); data_.pop_back(); return v; }
std::string& top() { return data_.back(); }
bool empty() const { return data_.empty(); }
size_t size() const { return data_.size(); }
std::string serialize() const {
std::ostringstream oss;
oss << "[";
for (size_t i=0; i<data_.size(); ++i) {
if (i) oss << ",";
oss << '"' << data_[i] << '"'; // JSON-quoted strings
}
oss << "]";
return oss.str();
}
friend std::ostream& operator<<(std::ostream& os, const Stack& s) {
return os << s.serialize();
}
};
// ── Variadic factory - make_stack(args...) ────────────────────
template<typename T, typename... Args>
Stack<T> make_stack(T first, Args... rest) {
Stack<T> s;
s.push(std::move(first));
(s.push(std::move(rest)), ...); // fold expression!
return s;
}
// ── Stack size checker type trait ────────────────────────────
template<typename> struct StackTraits {
static constexpr bool is_pointer_stack = false;
};
template<typename T> struct StackTraits<Stack<T*>> {
static constexpr bool is_pointer_stack = true;
};
int main() {
// Primary template - int
auto si = make_stack(10, 20, 30, 40);
std::cout << "int stack: " << si << "
"; // [10,20,30,40]
std::cout << "top=" << si.top() << "
"; // 40
// String specialisation - JSON-quoted
auto ss = make_stack<std::string>("hello", "world", "foo");
std::cout << "str stack: " << ss << "
"; // ["hello","world","foo"]
// Double stack
auto sd = make_stack(1.1, 2.2, 3.3);
std::cout << "dbl stack: " << sd << "
"; // [1.1,2.2,3.3]
// pop
while (!si.empty()) {
std::cout << "pop: " << si.pop_top() << " ";
}
std::cout << "
";
// Type traits check
std::cout << StackTraits<Stack<int>>::is_pointer_stack << "
"; // 0
std::cout << StackTraits<Stack<int*>>::is_pointer_stack << "
"; // 1
return 0;
}Common Mistakes
- Full specialisation doesn't inherit the primary template - `Stack<std::string>` has no relation to `Stack<T>` in terms of members. If you add a method to the primary template, you must add it to ALL specialisations manually.
- Fold expression with comma - `(s.push(std::move(rest)), ...)` evaluates left to right. The comma operator here sequences side effects. This is NOT the same as `...` unpacking inside a function call.
- `make_stack` with uniform type inference - `make_stack(1, 2, 3.0)` fails because `first` deduces as `int` but `3.0` is `double`. All args must be the same type. Fix: `make_stack(1, 2, static_cast<int>(3.0))` or add explicit template arg `make_stack<double>(1, 2, 3.0)`.
Tip
Tip
Practice Mini Project Part 7 Generic Stack Template in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
LIFO Container Template with Dynamic Resizing, Exception Safety & Move Semantics
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Part 7 Generic Stack Template 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 Mini Project Part 7 Generic Stack Template 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
- Build a production-ready generic `Stack<T>` with full specialisation for `Stack<std::string>` (JSON-safe serialisation), partial specialisation `Stack<T*>` (pointer semantics), and a variadic `make_stack(args.
- Full specialisation doesn't inherit the primary template - `Stack<std::string>` has no relation to `Stack<T>` in terms of members. If you add a method to the primary template, you must add it to ALL specialisations manually.
- Fold expression with comma - `(s.push(std::move(rest)), ...)` evaluates left to right. The comma operator here sequences side effects. This is NOT the same as `...` unpacking inside a function call.
- `make_stack` with uniform type inference - `make_stack(1, 2, 3.0)` fails because `first` deduces as `int` but `3.0` is `double`. All args must be the same type. Fix: `make_stack(1, 2, static_cast<int>(3.0))` or add explicit template arg `make_stack<double>(1, 2, 3.0)`.
Finished this lesson?