Skip to content

Template Method

Difficulty: Intermediate

Key concepts

  • template method pattern
  • algorithm skeleton
  • primitive operation
  • hook
  • non-virtual interface idiom
  • fragile base class
  • The problem Template Method solves, shown before the pattern is named: several procedures that follow the same steps and differ in a few of them, and the bugs that appear when each is written separately.
  • How to separate the fixed steps from the steps that vary.
  • The parts of the pattern: the template method, the primitive operations a derived class must supply, and hooks it may override.
  • The C++ non-virtual interface idiom: a public non-virtual function that calls private virtual ones.
  • Why inheritance makes this design fragile, and when the Strategy version is better.

A gym is moving its member list into a new system. Members arrive in two formats: a CSV export from the old website, and blocks of key: value lines sent by a partner gym.

Requirements:

  1. FR-1 Import members from CSV (one line per member, id,name,email; the first line may be a header) and from key-value blocks (one block per member, blocks separated by a blank line).
  2. FR-2 Every member must have a positive whole-number id, a name that is not empty, and an email that contains @.
  3. FR-3 Ids are unique. A record whose id is already in the directory is rejected.
  4. FR-4 A record that breaks a rule, or cannot be read, is reported with its position and a reason. The rest of the input is still imported.
  5. FR-5 Blank lines are ignored.

FR-2 to FR-5 are the same for every format. Only reading the text differs. (Reading the id as a positive number is part of reading the text, so it is the one FR-2 rule each format applies, through a shared helper.) That sentence, “the same except for…”, is the signal for this pattern.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

member.hpp
// One club member, as it is stored once an import has accepted it. A plain
// struct: three public fields and no rules of its own. The checks (a name,
// an '@' in the email, a unique id) live in the import, not here. The
// strings are owned copies, so a stored Member never points into the
// input text it was read from.
struct Member {
int id;
std::string name;
std::string email;
};
// Members by id. Ids are unique. This is where an import puts the members
// it accepts. `final` means no class can inherit from it.
class MemberDirectory final {
public:
// True if a member with this id is already stored.
bool contains(int id) const;
// Stores the member. Takes it by value, so the caller can std::move a
// Member in and no extra copy of its strings is made.
// Throws std::invalid_argument if a member with that id exists, and then
// stores nothing.
void add(Member member);
std::size_t size() const;
// Read-only access to every member. Returns a reference, not a copy, so
// it stays valid only while the directory exists.
const std::map<int, Member>& members() const;
private:
// std::map keeps its entries sorted by key, so members come out in id
// order, and looking an id up is fast (logarithmic in the size).
std::map<int, Member> members_;
};
// One record the import refused, and why.
struct Rejection {
std::size_t record; // 1-based position in the input
std::string reason;
};
// What one import did: how many members it stored, and the records it
// refused, in input order. A refused record is reported here, not thrown,
// so one bad record does not stop the others from being imported.
struct ImportReport {
int imported = 0;
std::vector<Rejection> rejected;
};

Where Template Method shows up in requirements. Listen for “every import (export, report, payment) must…”, followed by a list of steps, then “the only difference is how we read (write, format) it”. In code, the signal is two or more functions with the same shape: the same loop, the same checks, the same bookkeeping, with a few lines that differ in the middle. The pattern is common in import and export code, report generators, and frameworks that call your code at fixed points; in application code, a function that takes the varying step as a parameter is often enough.

The first version has one function per format. The CSV import came first; the key-value import was written later by copying it and changing the parsing:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// The first version: one function that does the whole CSV import, from
// raw text to stored members. Input: the text (one member per line,
// "id,name,email", maybe with a header line first) and the directory to
// add to. Result: a report of how many were stored and which lines were
// refused, and why. A bad line is reported and the loop moves on to the
// next one. The next function is a copy of this one with the reading
// part changed, and that copy is where the trouble starts.
ImportReport import_csv(std::string_view text, MemberDirectory& directory) {
ImportReport report;
// Cut the text at each newline. The pieces are std::string_view: views
// into `text` itself, so nothing is copied (see text.hpp).
const std::vector<std::string_view> lines = split(text, '\n');
for (std::size_t i = 0; i < lines.size(); ++i) {
// trim drops spaces, tabs, and '\r' from both ends of the line.
const std::string_view line = trim(lines[i]);
// Skip blank lines, and the header, which can only be the first line.
if (line.empty() || (i == 0 && line.starts_with("id,"))) {
continue;
}
// Everything that can go wrong while reading the line throws
// ParseError; the catch at the bottom turns it into a rejection.
try {
const std::vector<std::string_view> fields = split(line, ',');
if (fields.size() != 3) {
throw ParseError{"expected 3 fields, found " + std::to_string(fields.size())};
}
// parse_id throws ParseError unless the text is a positive whole
// number. std::string{...} copies each view into a string the
// Member owns, so the member does not depend on `text`.
Member member{parse_id(trim(fields[0])), std::string{trim(fields[1])},
std::string{trim(fields[2])}};
// The shared rules, written out here. The record number is
// `i + 1` because people count lines from 1, not 0. The braces
// `{i + 1, "..."}` make the Rejection (record, reason) that is pushed.
if (member.name.empty()) {
report.rejected.push_back({i + 1, "name is empty"});
} else if (member.email.find('@') == std::string::npos) {
report.rejected.push_back({i + 1, "email has no '@'"});
} else if (directory.contains(member.id)) {
// Checking first means add() below never sees a duplicate,
// so it never throws here.
report.rejected.push_back({i + 1, "duplicate id " + std::to_string(member.id)});
} else {
// std::move hands the member's strings to the directory
// instead of copying them; `member` is not used again.
directory.add(std::move(member));
++report.imported;
}
} catch (const ParseError& error) {
// error.what() is the message the throw was given.
report.rejected.push_back({i + 1, error.what()});
}
}
return report;
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// The second version, written later by copying import_csv and changing how
// the text is read. Each member is a block of "key: value" lines, and a
// blank line separates the blocks. The reading part is new; the checking
// part was copied by hand, and two things were lost on the way (marked
// below). Same inputs and result as import_csv.
ImportReport import_key_value(std::string_view text, MemberDirectory& directory) {
ImportReport report;
// One view per block of non-blank lines; blank blocks never appear.
const std::vector<std::string_view> blocks = split_blocks(text);
for (std::size_t i = 0; i < blocks.size(); ++i) {
try {
// Key to value, for this block only. std::less<> lets
// fields.contains("id") compare the text "id" with the stored
// keys directly, without first building a std::string from it.
std::map<std::string, std::string, std::less<>> fields;
for (const std::string_view line : split(blocks[i], '\n')) {
// find returns npos ("not found") when the line has no ':'.
const std::size_t colon = line.find(':');
if (colon == std::string_view::npos) {
throw ParseError{"expected 'key: value'"};
}
// Left of the colon is the key, right of it the value, both
// trimmed and copied into strings. fields[key] adds the key
// if it is new; a key that appears twice keeps the last value.
fields[std::string{trim(line.substr(0, colon))}] =
std::string{trim(line.substr(colon + 1))};
}
// All three keys must be present. The loop runs over a brace
// list of three string literals, one key per pass.
for (const char* key : {"id", "name", "email"}) {
if (!fields.contains(key)) {
throw ParseError{std::string{"missing "} + key};
}
}
// Safe to use fields["id"] here: every key is known to exist.
Member member{parse_id(fields["id"]), fields["name"], fields["email"]};
// Drift 1: the empty-name check was never copied, so a member
// with "name:" and nothing after it is accepted.
if (member.email.find('@') == std::string::npos) {
report.rejected.push_back({i + 1, "email has no '@'"});
} else {
// Drift 2: there is no directory.contains check before this
// call. add() throws std::invalid_argument on a duplicate id,
// and the catch below only catches ParseError, so the
// exception leaves the function: the import stops halfway,
// the members before it stay stored, and no report comes back.
directory.add(std::move(member)); // throws on a duplicate id
++report.imported;
}
} catch (const ParseError& error) {
report.rejected.push_back({i + 1, error.what()});
}
}
return report;
}

Read them side by side. They have drifted apart:

Step import_csv import_key_value
Split into records lines blocks
Skip a header yes, on the first line not needed
Read one record three comma-separated fields key: value lines
Empty name (FR-2) rejected accepted: the check was never copied
Email without @ rejected rejected
Duplicate id (FR-3) rejected and reported directory.add throws, and the import stops halfway

The last row is the worst. MemberDirectory::add throws std::invalid_argument on a duplicate, and import_key_value catches only ParseError. So a duplicate stops the whole import, and the members before it are already stored while the ones after it are not. Nobody wrote that on purpose; the second copy simply missed a check. These tests pin both differences:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_import.cpp
// Pins the drift between the two copied functions.
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false. LLD_CHECK_EQ(actual, expected) fails unless
// the two are equal. LLD_CHECK_THROWS(expression, type) fails unless the
// expression throws that type of exception. They come from the site's
// small test header, lld_test.hpp. `std::size_t{1}` writes 1 with the same
// type that size() returns, so the two sides compare without a warning.
//
// duplicate_blocks, defined at the top of this file, holds three blocks:
// Dana Fox (id 5), Dana Twin (id 5 again), and Fay Lum (id 7).
//
// Proves drift 2: the duplicate makes add() throw out of the function, so
// Dana Fox is stored, and Fay Lum, after the duplicate, never is.
LLD_TEST(before_the_key_value_import_stops_halfway_on_a_duplicate_id) {
MemberDirectory directory;
LLD_CHECK_THROWS(before::import_key_value(duplicate_blocks, directory),
std::invalid_argument);
LLD_CHECK_EQ(directory.size(), std::size_t{1}); // Fay was never imported
}
// Proves drift 1: "name:" with nothing after it gives an empty name, and
// the key-value copy stores the member anyway.
LLD_TEST(before_the_key_value_import_accepts_an_empty_name) {
MemberDirectory directory;
const ImportReport report =
before::import_key_value("id: 8\nname:\nemail: x@example.com\n", directory);
LLD_CHECK_EQ(report.imported, 1); // the CSV import would refuse this
}

This is the cost of duplicated steps, not just duplicated lines: every rule that applies to all formats lives in each copy, and each copy can get it wrong separately. The DRY page calls this duplicated knowledge.

Step 1: separate the fixed steps from the varying ones

Section titled “Step 1: separate the fixed steps from the varying ones”

List the steps of one import and ask, for each, whether it is the same for every format:

# Step Same for every format? Who should own it
1 Split the text into records no: lines or blocks each format
2 Skip a header record no, but most formats have none each format, with a default
3 Read one record into a Member no each format
4 Check the name, email, and duplicate id (FR-2, FR-3) yes written once
5 Store the member, or report why not (FR-4) yes written once
– The order of the steps, and the loop yes written once

The fixed parts include the order: no format may store a member before checking it. So the code that runs the steps must be written once, and a format must not be able to change it.

That is the Template Method pattern.

Role What it does In this example
Template method The fixed steps, in order; not virtual Importer::run
Primitive operations Steps every derived class must supply; pure virtual split_records, parse_record
Hook A step with a default that a derived class may override is_header (default: no header)
Concrete classes Supply the steps for one variant CsvImporter, KeyValueImporter

The name has nothing to do with C++ templates. “Template” here means a fixed outline with blanks for the derived classes to fill in.

class Importer

abstract base

Member functions

  • ImportReport run(std::string_view text, MemberDirectory& directory) const; the template method; not virtual
  • virtual ~Importer() = default;
  • virtual std::vector<std::string_view> split_records(std::string_view text) const = 0; private: a primitive operation
  • virtual Member parse_record(std::string_view record) const = 0; private: throws ParseError
  • virtual bool is_header(std::size_t index, std::string_view record) const; private: a hook, default false

class CsvImporter final

is an Importer

Member functions

  • std::vector<std::string_view> split_records(std::string_view text) const override; private; lines
  • bool is_header(std::size_t index, std::string_view record) const override; private; "id," on line 1
  • Member parse_record(std::string_view record) const override; private; id,name,email

class KeyValueImporter final

is an Importer

Member functions

  • std::vector<std::string_view> split_records(std::string_view text) const override; private; blocks
  • Member parse_record(std::string_view record) const override; private; key: value lines
The base class owns the steps and the order; each format fills in only its own steps

In this outline, the note “private” marks the private member functions, because in this design the virtual steps are private. None of these classes has a data member: an importer holds no state between calls. The protected constructor and copy operations of Importer are left out.

Two formats are an Importer; run uses the directory and creates a report; main uses the formats
Text description of the diagram

A thick arrow means “is a” (implements or inherits), a dashed arrow means “uses”, and a solid arrow means flow or creation. CsvImporter and KeyValueImporter each have a thick arrow labelled “is a” to Importer, whose run function holds the fixed steps. Importer has a dashed arrow labelled “checks and adds to” to MemberDirectory and a solid arrow labelled “creates” to ImportReport. main has dashed “uses” arrows to CsvImporter and KeyValueImporter.

Diagram source (Mermaid)
flowchart TB
MN["main"] -.->|uses| CI
MN -.->|uses| KI
CI["CsvImporter"] ==>|is a| IM["Importer<br/>run: the fixed steps"]
KI["KeyValueImporter"] ==>|is a| IM
IM -.->|checks and adds to| MD["MemberDirectory"]
IM -->|creates| RP["ImportReport"]

The base class: steps fixed, blanks private

Section titled “The base class: steps fixed, blanks private”

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

importer.hpp
// The template method: run() fixes the steps of every import, in order.
// A format supplies only the steps that differ.
// Importer is abstract: it has pure virtual functions (the `= 0` ones), so
// no plain Importer can be made. A format is a class derived from it that
// fills in those steps, such as CsvImporter.
class Importer {
public:
// Virtual, so that deleting a format through an Importer pointer (for
// example a std::unique_ptr<Importer>) runs the format's destructor too.
virtual ~Importer() = default;
// Not virtual: no format can change the order of the steps or skip
// the checks. Records that cannot be imported are reported, not
// thrown, and the rest of the input is still imported.
ImportReport run(std::string_view text, MemberDirectory& directory) const;
protected:
// Protected: only derived classes can use these. A CsvImporter can
// still be built and copied, but code outside the hierarchy cannot
// copy "just the Importer part" of one (that mistake is called slicing).
Importer() = default;
Importer(const Importer&) = default;
Importer& operator=(const Importer&) = default;
private:
// Private virtual functions: a derived class may override them, but only
// Importer's own code (run) may call them, so no step can be run on its
// own, outside the fixed order.
// `= 0` means "pure virtual": there is no default, every format must
// supply its own.
// Step 1, cutting the text into records. The views returned must point
// into `text` itself, not into a local string that dies on return.
virtual std::vector<std::string_view> split_records(std::string_view text) const = 0;
// Step 3, turning one record into a Member.
// Throws ParseError if the record cannot be read.
virtual Member parse_record(std::string_view record) const = 0;
// A hook: a step with a default that a format may override.
// Step 2: should the record at this 0-based index be skipped as a
// header? The default, in importer.cpp, says no.
virtual bool is_header(std::size_t index, std::string_view record) const;
};

This layout is the non-virtual interface idiom (often shortened to NVI):

  • The public function is not virtual. Callers call run, and every call goes through the same steps. No derived class can override run and skip the checks.
  • The virtual functions are private. A derived class can still override a private virtual function; C++ allows it, because overriding is about which function runs, not about who may call it. But only Importer’s own code can call the steps, so nobody can call parse_record on its own and store the result without the checks.
  • A step is protected instead only when a derived class must call the base version of it, for example to add to a default instead of replacing it. No step here needs that.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

importer.cpp
// The template method. Every import, whatever the format, goes through
// these five steps in this order. Calls to split_records, is_header, and
// parse_record are virtual calls: they run the version of the format this
// importer really is (CsvImporter or KeyValueImporter). The rest is
// written once, here.
// Input: the text and the directory to add to. Result: the report. A bad
// record is reported and skipped. Only ParseError is caught; any other
// exception (out of memory, say) leaves run, and members stored before it
// stay stored.
ImportReport Importer::run(std::string_view text, MemberDirectory& directory) const {
ImportReport report;
const std::vector<std::string_view> records = split_records(text); // step 1: format
for (std::size_t i = 0; i < records.size(); ++i) {
const std::string_view record = trim(records[i]);
// A blank record is skipped silently, before the hook is even asked.
if (record.empty() || is_header(i, record)) { // step 2: hook
continue;
}
try {
Member member = parse_record(record); // step 3: format
// problem_with (above, in this file) returns an empty
// std::optional if the member is fine, or the reason to reject
// it. Declaring `problem` inside the `if` keeps it local to the
// check, and an optional that holds a reason counts as true.
// *problem is the reason string inside it.
if (const auto problem = problem_with(member, directory)) { // step 4: shared
report.rejected.push_back({i + 1, *problem});
continue; // on to the next record; this one is not stored
}
// Step 4 already ruled out a duplicate id, so add() does not
// throw here. std::move hands over the strings without copying.
directory.add(std::move(member)); // step 5: shared
++report.imported;
} catch (const ParseError& error) {
// Thrown by parse_record (or parse_id inside it): this record
// could not be read. Report it, 1-based, and carry on.
report.rejected.push_back({i + 1, error.what()});
}
}
return report;
}
// The hook's default. The parameter names are in /* */ comments because
// this version does not use them; leaving them unnamed avoids an "unused
// parameter" warning while still saying what they are.
bool Importer::is_header(std::size_t /*index*/, std::string_view /*record*/) const {
return false; // most formats have no header
}

The comments number the steps from the table in Step 1. Steps 1–3 are calls to virtual functions; steps 4 and 5 are ordinary code that every format shares. problem_with, in an unnamed namespace in the same file, holds the name, email, and duplicate-id checks, once. The id itself is read by parse_id, a helper in text.hpp that both formats call inside parse_record; it throws ParseError for text that is not a positive number.

run catches only ParseError, the one exception that means “this record is bad”. A bad record is expected, so it is reported and the loop goes on (FR-4). Anything else, such as std::bad_alloc, means the import itself failed; it is not caught, and it leaves run. So does an exception from split_records, which runs before the loop.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

formats.hpp
// One line per member: id,name,email. The first line may be a header.
// Supplies the two required steps and replaces the is_header hook.
// `final`: nothing may derive from it. `override` asks the compiler to
// check that each function really replaces a virtual one in Importer, so a
// typo in a name or parameter type is an error instead of a new function.
// The overrides stay private, as in Importer: callers use run(), which is
// public in the base class.
class CsvImporter final : public Importer {
private:
std::vector<std::string_view> split_records(std::string_view text) const override;
bool is_header(std::size_t index, std::string_view record) const override;
Member parse_record(std::string_view record) const override;
};
// One block per member, blocks separated by a blank line:
// id: 5
// name: Dana Fox
// email: dana@example.com
// Supplies only the two required steps; it keeps the default is_header,
// which never skips a record.
class KeyValueImporter final : public Importer {
private:
std::vector<std::string_view> split_records(std::string_view text) const override;
Member parse_record(std::string_view record) const override;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

formats.cpp
// Step 1 for CSV: one record per line. The views point into `text`, as
// run() requires. Text that ends in '\n' gives one last empty record,
// which run() skips as blank.
std::vector<std::string_view> CsvImporter::split_records(std::string_view text) const {
return split(text, '\n');
}
// Step 2 for CSV: only the very first record can be the header line.
bool CsvImporter::is_header(std::size_t index, std::string_view record) const {
return index == 0 && record.starts_with("id,");
}
// Step 3 for CSV: "7, Ann Bo , ann@example.com" becomes Member{7, "Ann Bo",
// "ann@example.com"}; spaces around each field are trimmed.
// Throws ParseError if there are not exactly 3 fields, or (from parse_id)
// if the id is not a positive whole number. It does not check the name or
// email: run() does that for every format.
Member CsvImporter::parse_record(std::string_view record) const {
const std::vector<std::string_view> fields = split(record, ',');
if (fields.size() != 3) {
throw ParseError{"expected 3 fields, found " + std::to_string(fields.size())};
}
// `return {...}` builds the Member from the braces; the return type
// says which type to build. std::string{...} copies each view, so the
// Member owns its text.
return {parse_id(trim(fields[0])), std::string{trim(fields[1])},
std::string{trim(fields[2])}};
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

formats.cpp
// Step 1 for key-value text: one record per block of non-blank lines.
std::vector<std::string_view> KeyValueImporter::split_records(std::string_view text) const {
return split_blocks(text);
}
// Step 3 for key-value text: reads every "key: value" line of the block
// into a map, then builds the Member from the three keys it needs.
// Throws ParseError if a line has no ':', if id, name, or email is
// missing, or (from parse_id) if the id is not a positive whole number.
// Keys it does not know are read and then ignored.
Member KeyValueImporter::parse_record(std::string_view record) const {
// Key to value for this one block. std::less<> lets fields.contains
// look up a plain "id" without first building a std::string from it.
std::map<std::string, std::string, std::less<>> fields;
for (const std::string_view line : split(record, '\n')) {
// npos means "not found": this line has no ':' at all.
const std::size_t colon = line.find(':');
if (colon == std::string_view::npos) {
throw ParseError{"expected 'key: value'"};
}
// substr(0, colon) is the text before the colon (the key);
// substr(colon + 1) is everything after it (the value). Both are
// trimmed and copied into owned strings. fields[key] adds the key if
// it is new; if a key appears twice, the last value wins.
fields[std::string{trim(line.substr(0, colon))}] =
std::string{trim(line.substr(colon + 1))};
}
// The loop walks a brace list of three keys, one per pass.
for (const char* key : {"id", "name", "email"}) {
if (!fields.contains(key)) {
throw ParseError{std::string{"missing "} + key};
}
}
// All three keys are known to exist, so fields["..."] only reads here.
// The strings are copied into the Member.
return {parse_id(fields["id"]), fields["name"], fields["email"]};
}
How this code works: KeyValueImporter::parse_record

run hands parse_record one block at a time. Take the second block of the key-value input in main.cpp:

id: 6
name: Eli Moss
  1. Read every line into the map. split(record, '\n') gives two lines. For id: 6, find(':') returns 2, so the key is the text before position 2, id, and the value is everything after it, 6, trimmed to 6. The second line adds name → Eli Moss. A line with no colon would throw ParseError with “expected ‘key: value’” at once.
  2. Check that the three keys are there. The loop asks for id, then name, then email. The first two are found; email is not, so it throws ParseError with “missing email”.
  3. run catches it. The block is reported as record 2, “missing email”, which is the line you see in the output below, and run goes on to the third block.

When all three keys are present, the last line builds the Member: parse_id turns the text 6 into the number 6 (or throws if it is not a positive number), and the name and email are copied into the member. Nothing here checks for an empty name, a missing @, or a duplicate id. That is on purpose: those checks are step 4 of run, shared by every format, so this function cannot forget them the way the copied function did.

Each format is now only about reading text. KeyValueImporter does not override is_header, so it gets the default. Both classes are final: nothing should derive from a format, and final says so.

One call to run on a CsvImporter: the base class calls the format's steps, then does the shared steps itself
Text description of the diagram

main calls Importer::run with the CSV text and the directory. run calls the CsvImporter’s split_records and gets the lines back. Then, for each record that is not empty, run calls is_header (true only for the first line) and parse_record, which returns a Member or throws ParseError. run asks the directory whether the id is already there, and calls add only if every check passed. Finally run returns the ImportReport to main. Importer::run and the CsvImporter steps are the same object; the diagram shows them apart to make clear which code runs.

Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant I as Importer::run
participant C as CsvImporter steps
participant D as MemberDirectory
M->>I: run(csv_text, directory)
I->>C: split_records(text)
C-->>I: lines
loop each record that is not empty
  I->>C: is_header(i, record)
  C-->>I: true only for line 1
  I->>C: parse_record(record)
  C-->>I: Member, or throws ParseError
  I->>D: contains(id)
  D-->>I: bool
  I->>D: add(member), if every check passed
end
I-->>M: ImportReport
Object Owner Lives
The input text the caller at least until run returns
Each record nobody: a std::string_view into the text only inside run
Each Member run, then the directory moved into the directory when stored
The directory the caller run borrows it through a reference
The importers the caller no data members; one const importer can run many imports

The records are views into the caller’s text, so they cost no copying. That is safe because they never leave run. It is also a contract on every format: split_records must return views into text itself. A format that built a local std::string and returned views into it would hand run dangling views, and the compiler would not notice. A Member holds its own std::string copies of the fields, so nothing stored in the directory points into the input text. If a member kept a std::string_view into the input instead, the directory would dangle as soon as the caller freed the text.

Importer has a public virtual destructor because a program might choose a format at run time and hold it as std::unique_ptr<Importer>. Deleting a CsvImporter through that pointer must run the right destructor.

The input has a header and five members:

  1. split_records returns 7 records: 6 lines and the empty string after the final newline.
  2. Record 1, id,name,email: is_header returns true → skipped.
  3. Record 2, 1,Kim Lee,kim@example.com: parsed, checks pass → stored; imported = 1.
  4. Record 3, 2,Sam Roy,sam.example.com: parsed; no @ → rejected, “email has no ‘@’”.
  5. Record 4, 3,,ana@example.com: parsed; empty name → rejected.
  6. Record 5, 1,Kim Again,…: parsed; id 1 is in the directory → rejected, “duplicate id 1”. The import continues.
  7. Record 6, 4,Lee Park: parse_record throws ParseError → rejected, “expected 3 fields, found 2”.
  8. Record 7 is empty → skipped (FR-5). run returns the report.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// One directory, filled by two imports in turn. The importers hold no
// data, so they can be const: run() is a const function.
MemberDirectory directory;
const CsvImporter csv;
const KeyValueImporter key_value;
// csv_text and key_value_text are defined at the top of main.cpp. print,
// also defined there, writes the counts and each rejection.
// The second import sees the members the first one stored, so a
// key-value member with a CSV member's id would be a duplicate.
print("csv", csv.run(csv_text, directory));
print("key-value", key_value.run(key_value_text, directory));
std::cout << "directory:";
// Each map entry is an (id, member) pair; `const auto& [id, member]`
// names its two halves without copying them. A std::map walks in key
// order, so the members print sorted by id.
for (const auto& [id, member] : directory.members()) {
std::cout << ' ' << id << ' ' << member.name << ';';
}
std::cout << '\n';
Expected output
csv: 1 imported, 4 rejected
record 3: email has no '@'
record 4: name is empty
record 5: duplicate id 1
record 6: expected 3 fields, found 2
key-value: 1 imported, 2 rejected
record 2: missing email
record 3: duplicate id 5
directory: 1 Kim Lee; 5 Dana Fox;

The key-value import now rejects the duplicate id 5 and carries on, which the copied function could not do.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_import.cpp
// The same two inputs that broke the copied function, now run through the
// template method. The duplicate is rejected and the import goes on, and
// the empty name is refused, because both formats share run()'s checks.
// KeyValueImporter{} makes a temporary importer just for this one call.
LLD_TEST(every_format_gets_the_same_checks) {
MemberDirectory directory;
const ImportReport report = KeyValueImporter{}.run(duplicate_blocks, directory);
LLD_CHECK_EQ(report.imported, 2); // Dana Fox and Fay Lum
LLD_CHECK_EQ(report.rejected.size(), std::size_t{1});
LLD_CHECK(report.rejected[0].reason == "duplicate id 5");
// Same directory, now holding ids 5 and 7; id 8 has an empty name.
const ImportReport empty_name =
KeyValueImporter{}.run("id: 8\nname:\nemail: x@example.com\n", directory);
LLD_CHECK_EQ(empty_name.imported, 0);
LLD_CHECK(empty_name.rejected[0].reason == "name is empty");
}
// The hook is_header only says yes for record index 0. The same text on
// the third line is read as a member, and its id "id" is not a number,
// so it is rejected as record 3.
LLD_TEST(the_csv_header_is_skipped_only_on_the_first_line) {
MemberDirectory directory;
const ImportReport report =
CsvImporter{}.run("id,name,email\n1,Kim,kim@example.com\nid,name,email\n", directory);
LLD_CHECK_EQ(report.imported, 1);
LLD_CHECK_EQ(report.rejected.size(), std::size_t{1});
LLD_CHECK_EQ(report.rejected[0].record, std::size_t{3});
}
// A ParseError from parse_record is caught by run(): the bad record is
// reported and the next one is still imported. Checked for a bad CSV id,
// and for a key-value line with no ':'.
LLD_TEST(a_record_that_cannot_be_read_is_reported_and_the_rest_imported) {
MemberDirectory directory;
const ImportReport report =
CsvImporter{}.run("x,Kim,kim@example.com\n2,Sam,sam@example.com\n", directory);
LLD_CHECK_EQ(report.imported, 1);
LLD_CHECK(report.rejected[0].reason == "id 'x' is not a positive number");
const ImportReport blocks = KeyValueImporter{}.run("id 9\n", directory);
LLD_CHECK(blocks.rejected[0].reason == "expected 'key: value'");
}
// Blank records are skipped, not rejected: the CSV text still imports its
// one member, and text with only newlines gives no blocks at all.
LLD_TEST(blank_lines_and_blank_blocks_are_ignored) {
MemberDirectory directory;
LLD_CHECK_EQ(CsvImporter{}.run("\n\n1,Kim,kim@example.com\n\n", directory).imported, 1);
LLD_CHECK_EQ(KeyValueImporter{}.run("\n\n\n", directory).rejected.size(), std::size_t{0});
}
// The helper on its own: two blank lines in a row still make one break,
// and the lines of a block stay joined by their '\n'.
LLD_TEST(split_blocks_keeps_each_group_of_lines_together) {
const auto blocks = split_blocks("a\nb\n\n\nc\n");
LLD_CHECK_EQ(blocks.size(), std::size_t{2});
LLD_CHECK(blocks[0] == "a\nb");
LLD_CHECK(blocks[1] == "c");
}

every_format_gets_the_same_checks runs the very inputs that broke the copied function, through KeyValueImporter. The duplicate is rejected and the member after it is imported; the empty name is refused. Those two bugs are now impossible to reintroduce in one format only, because no format contains those checks. The rule a format can still get wrong is the one it applies itself: a new format that read the id without parse_id could accept id 0. Everything that is written in run is safe from that; everything left to the formats is not. The guarantee also covers only the import path: other code could still call directory.add directly.

Template Method uses inheritance: each format is an Importer. That couples the formats to the base class more tightly than you might expect. This is often called the fragile base class problem.

  • The formats depend on how the base calls them. A format’s steps are written assuming run calls split_records once and then parse_record once per record. Suppose someone later changes run to parse every record twice, once to count and once to store. A format whose parse_record writes to a log would now log everything twice. Nothing in the types warns about it.
  • Every format must fit the skeleton. A JSON array cannot be split into records without parsing it. A JSON importer would have to parse inside split_records and then parse again in parse_record, or break the skeleton.
  • Variations multiply. If a second step also varied, for example whether a rejected record stops the import or is skipped, and the format is CSV or key-value, inheritance needs a class per combination. Composition keeps each axis separate (see the exercise).
  • The format is fixed for the life of the object. A CsvImporter is always CSV. That is rarely a problem for an import, but it is for behaviour that must change while running.

None of these hurt here: the skeleton is short and stable, the formats are owned by the same team, and there are two of them. That is the situation where Template Method is a good fit.

Both patterns let one piece of code keep fixed steps while another supplies the varying part. The difference is how the varying part is attached:

Question Template Method Strategy
How is the varying part supplied? by inheriting and overriding steps by holding an object that does the job
Who owns the fixed steps? the base class the context class
Can the variant change at run time? no: it is the object’s class yes: swap the object
Can two kinds of variation combine? only with a class per combination yes: hold two strategy objects
Can the varying part be tested alone? only through run, since the steps are private (often enough) yes: it is an ordinary object
How many types? fewer: the base and one class per variant one more: the strategy interface

A rule of thumb: prefer Strategy when the variation could change at run time, could combine with another variation, or should be tested on its own. Choose Template Method when the skeleton must be enforced, the variants are few and stable, and the varying steps need little state. The exercise below converts this page’s design to Strategy so that you can compare them directly.

When to use Template Method, and when not to

Section titled “When to use Template Method, and when not to”

Use it when:

  • several procedures share the same steps in the same order, and the shared steps include rules that must never be skipped;
  • the steps that vary are few, small, and fit one skeleton;
  • the variants belong to the same codebase and change together with the base class.

Do not use it when:

  • there is one variant. A plain function is clearer.
  • the variants differ only in data: a tab-separated import differs from CSV only in the separator character. Make the separator a constructor parameter of CsvImporter; do not add a class.
  • one or two callbacks would do. A function that takes the varying steps as parameters, for example run_import(text, directory, split, parse) with std::function parameters, gives the same guarantee with no class hierarchy at all.
  • the variation must change at run time, or several variations combine. Use Strategy.
Approach Good for Costs
Copied functions, one per variant a one-off script shared rules drift apart, as the table above shows
Template Method with NVI a fixed skeleton with rules that must not be skipped inheritance coupling; the variant is fixed per object
One function with callback parameters one or two varying steps, no state long parameter lists if the steps grow
Strategy (the skeleton holds a format object) variants that combine, change at run time, or are tested alone one more interface; the context must manage the object’s lifetime
  • Making the template method virtual. Then a derived class can override run and skip the checks, and the pattern’s one guarantee is gone.
  • Public virtual steps. Callers can then call parse_record directly and store the result without the checks. Keep them private.
  • A hook for every line of the skeleton “for flexibility”. Each hook is another way a derived class can break the algorithm, and another thing to test. Add one when a variant needs it.
  • Deep hierarchies. CsvImporter → CsvWithHeaderImporter → QuotedCsvWithHeaderImporter is a sign that the variations should be data (constructor parameters) or separate objects.
  • Derived classes that must remember to call the base version of a step. That is a rule the compiler cannot check. If a step has a part that must always run, move that part into the template method.

“Also accept tab-separated files.” This differs from CSV only in one character. Give CsvImporter a constructor parameter char separator = ',' and a data member to store it, and use it in both is_header (the header starts with id and the separator) and parse_record. The importer now has one piece of state, set once and never changed, so a const importer can still run many imports. No new class, no new step.

“Write every rejection to the audit log.” This applies to every format, so it goes into the fixed part: one change in run, next to report.rejected.push_back. No format changes. This is the payoff of the pattern.

“Partner files may arrive compressed.” Decompressing is not a step of reading members; it happens before the import. Decompress, then pass the text to run. Adding a decompress hook to Importer would mix a transport concern into the parsing skeleton.

Exercise: Convert the import to Strategy, and compare

  1. Redesign the import so that the fixed steps live in a class that holds a format object instead of being inherited. Sketch the format interface and the class that runs the steps. Who owns the format?
  2. The partner gym asks for a strict mode: stop at the first rejected record and import nothing more, while the website import keeps reporting and carrying on. Now there are three formats (CSV, key-value, and a new fixed-width format) and two ways to handle a rejection. How many classes does each design need, and why?
  3. Which design would you keep for this gym’s import, and why? (More than one answer can be justified; say what would change your mind.)
Show the explained answer

1.

interface (abstract class) RecordFormat

the strategy: only how to read text

Member functions

  • virtual std::vector<std::string_view> split_records(std::string_view text) const = 0;
  • virtual bool is_header(std::size_t index, std::string_view record) const; default false
  • virtual Member parse_record(std::string_view record) const = 0; throws ParseError
  • virtual ~RecordFormat() = default;

class Importer final

the context: the same fixed steps as run() today

Data members

  • const RecordFormat& format_; not owned; must outlive the importer

Member functions

  • explicit Importer(const RecordFormat& format);
  • ImportReport run(std::string_view text, MemberDirectory& directory) const;
One possible answer: the format becomes a strategy; the fixed steps move into a final class that holds it

CsvFormat and KeyValueFormat implement RecordFormat. The steps of Importer::run are unchanged; it calls format_.split_records(text) and so on. The format’s functions are now public, because another class calls them; the guarantee that nobody skips the checks now comes from Importer being the only code that stores members, not from access control. Ownership is a choice: the formats are stateless, so a reference to one that lives in main is enough. If importers were created and kept in many places, owning it through std::unique_ptr<RecordFormat> would avoid the lifetime rule.

2. With Strategy, the rejection handling becomes a second, separate object, for example a RejectionPolicy interface with KeepGoing and StopAtFirst, and Importer holds one format and one policy: 3 + 2 = 5 classes, and any format works with any policy. With Template Method, the policy is also a step of the skeleton, so each combination is its own derived class (StrictCsvImporter, and so on): 3 × 2 = 6. In general, a formats and b policies cost a + b classes with Strategy and a × b with inheritance, and each new axis multiplies again. (A source such as “a file or a network stream” would not be a second axis here: getting the text happens before run is called.)

3. For the gym today, either is defensible. Template Method is slightly shorter, there are two formats, and the skeleton is stable, so the page keeps it. You would switch to Strategy if a second axis of variation appeared (the rejection policy, as in question 2), if the format had to be chosen and changed while running, or if you wanted to test each format’s parsing directly without going through run.

  • Strategy: varies the whole algorithm, or one job, through an object the context holds; Template Method varies steps through inheritance. See Strategy, and Strategy vs State vs Template Method.
  • Factory Method: a template method whose varying step is “create an object”, so the base class can use an object without knowing its concrete type. See Factory Method.
  • Hooks and callbacks: a function that takes std::function parameters is the lightweight, composition-based form of the same idea.
  • Template Method writes the fixed steps once, in a base-class function, and lets derived classes supply only the steps that vary.
  • Use the C++ non-virtual interface idiom: public non-virtual template method; private virtual steps; a hook is a virtual step with a default.
  • It removes a real bug class: shared rules that drift apart between copied procedures.
  • It couples variants to the base class through inheritance: they depend on how and when the base calls them, cannot change at run time, and multiply when variations combine.
  • Never call the template method from a constructor or destructor.
  • Prefer Strategy when variants combine, change while running, or should be tested alone; prefer a parameter when variants differ only in data.