bhylu.com

Advertisements

C++ Class Templates

Define a small typed history and let a standard container manage its elements.

How it works

A class template creates related class types parameterized by a type or constant. History<int> and History<string> are distinct types with separately checked member operations. Store resources in standard owners so the generated copy, move and destruction behaviour remains useful without manual allocation. Template definitions generally need to be visible where they are instantiated, which is why small template implementations often live in headers rather than ordinary separately compiled source files.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror class-templates.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · class-templates.cpp

#include <iostream>
#include <vector>
#include <string>
#include <utility>

template<class T>
class History {
    std::vector<T> entries_;
public:
    void add(T value) { entries_.push_back(std::move(value)); }
    std::size_t size() const { return entries_.size(); }
};

int main() {
    History<int> counts; counts.add(3); counts.add(5);
    History<std::string> names; names.add("Quay");
    std::cout << "Counts: " << counts.size() << "; names: " << names.size() << '\n';
}

Expected result

Counts: 2; names: 1

Each history owns its vector and the vector owns its elements. Moving the local parameter into the vector avoids an extra string copy where supported. Include utility explicitly for std::move instead of relying on transitive includes. Real history APIs should define retention and capacity limits; an unbounded vector is not automatically a suitable event store.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.