Skip to content

Test the Public Type Interface

The Course
•
35 min study

On Day 3 you tested one template's constraint at compile time. Today you test the whole public type interface of the engine the way a consumer sees it: what engine.h lets other code do with Engine, Rule and count_events, and what it forbids. These properties are design decisions, made for reasons: the engine is move-only because it owns its rules, the rule base is abstract with a virtual destructor because rules are deleted through base pointers, and snapshot returns an owning copy so callers cannot hold references into live state. A careless edit to the header could undo any of them without changing a single runtime result.

The project collects these checks in compile_contracts.cpp, a separate consumer file that includes only engine.h. It compiles if and only if the interface still has its intended shape. The two reject_*.cpp files complement it by showing the actual errors a consumer gets.

Predict and run

Predict before running C++
#include <iostream>
#include <memory>
#include <type_traits>

int main() {
    static_assert(!std::is_copy_constructible_v<std::unique_ptr<int>>);
    static_assert(std::is_move_constructible_v<std::unique_ptr<int>>);
    std::cout << "Move-only interface\n";
    return 0;
}
Check your prediction
Text
Move-only interface

Both assertions were decided before the program ran, which is why the only output is the line after them. They describe the type, not any particular object: no unique_ptr was created, and no resource was owned or freed. Whether a real engine destroys its rules exactly once is a runtime question, answered on Day 2 with a counter. Compile-time and runtime checks are different evidence about different claims, and the project needs both.

What belongs in the contract

A good interface test asserts the properties a consumer relies on and nothing else. For this engine:

  • Engine is not copy constructible or copy assignable, and is move constructible and move assignable.
  • Rule is abstract and has a virtual destructor.
  • snapshot() returns Inventory by value, not a reference into the engine.
  • apply accepts a std::vector<Event> and other contiguous event sequences, and rejects a sequence of the wrong element type.
  • count_events accepts a predicate over const Event& and refuses one over int.

Each property can be asserted with a type trait or a concept wrapping an expression:

Contract checks for a small engine C++
#include <concepts>
#include <iostream>
#include <map>
#include <memory>
#include <span>
#include <type_traits>
#include <vector>

struct Event { int id; int delta; };
using Inventory = std::map<int, int>;

class Rule {
public:
    virtual ~Rule() = default;
    virtual bool accepts(const Inventory& proposed) const = 0;
};

class Engine {
public:
    Engine() = default;
    Engine(const Engine&) = delete;
    Engine& operator=(const Engine&) = delete;
    Engine(Engine&&) = default;
    Engine& operator=(Engine&&) = default;
    bool apply(std::span<const Event> events) { return events.size() <= 256; }
    Inventory snapshot() const { return state_; }
private:
    Inventory state_;
    std::vector<std::unique_ptr<Rule>> rules_;
};

template<class Batch>
concept Appliable = requires(Engine& engine, const Batch& batch) { engine.apply(batch); };

static_assert(!std::is_copy_constructible_v<Engine> && !std::is_copy_assignable_v<Engine>);
static_assert(std::is_move_constructible_v<Engine> && std::is_move_assignable_v<Engine>);
static_assert(std::is_abstract_v<Rule> && std::has_virtual_destructor_v<Rule>);
static_assert(std::is_same_v<decltype(std::declval<const Engine&>().snapshot()), Inventory>);
static_assert(Appliable<std::vector<Event>>);
static_assert(!Appliable<std::vector<int>>);

int main() {
    std::cout << "Engine contracts compiled\n";
    return 0;
}
Text
Engine contracts compiled

std::declval<const Engine&>() pretends to produce a const Engine& in an unevaluated context, so the check needs no real engine and also proves snapshot can be called on a const engine. The Appliable concept checks the call itself, including the implicit conversion from a vector to a span.

Now try two harmful edits and watch the build stop. Change snapshot to return const Inventory&: the fourth assertion fails, which matters because a reference would let a caller observe the next batch's swap. Delete the four special member declarations: the first assertion fails, because a vector of unique_ptr declares a copy constructor even though using it would not compile, as you saw on Day 3.

What does not belong

Do not assert properties nobody should depend on: sizeof(Engine), the exact container behind rules_, whether a move is trivially copyable. Those are implementation details. A test that pins them fails on harmless refactors, and a test that fails for no reason teaches people to ignore failures. The contract is the set of facts a caller would be broken by losing.

Notice too that the test file includes only the header and touches only public names. That is deliberate. If a contract check needs private access, it is testing the implementation, not the interface.

Positive before negative

The course checker runs compile_contracts.cpp first and the reject files second. A negative test that "fails to compile" proves nothing if every file fails to compile, for example because the header has a typo or the compiler does not support C++20. Only after the valid consumer builds is a failure in reject_copy.cpp evidence that copying is refused. The checker then also looks for deleted in that file's error output, so an unrelated failure, such as a missing include, cannot pass for the intended one.

Practice

Exercise

Your turn

The starter declares a Ledger interface. Without changing the classes, write static_asserts proving that: Ledger cannot be copied but can be moved; Policy is abstract with a virtual destructor; entries() on a const ledger returns std::vector<int> by value; record accepts a std::vector<int> and an int array but not a std::vector<double>; and count_if_entry accepts a predicate over int but not one over const std::string&. Then print:

Shell
Public types checked
Your workspace C++
#include <concepts>
#include <iostream>
#include <memory>
#include <span>
#include <string>
#include <type_traits>
#include <vector>

class Policy {
public:
    virtual ~Policy() = default;
    virtual bool allows(int entry) const = 0;
};

class Ledger {
public:
    Ledger() = default;
    Ledger(const Ledger&) = delete;
    Ledger& operator=(const Ledger&) = delete;
    Ledger(Ledger&&) = default;
    Ledger& operator=(Ledger&&) = default;
    void record(std::span<const int> values) { entries_.insert(entries_.end(), values.begin(), values.end()); }
    std::vector<int> entries() const { return entries_; }
    template<class Predicate>
    requires std::predicate<Predicate, int>
    std::size_t count_if_entry(Predicate matches) const {
        std::size_t count = 0;
        for (int entry : entries_) { if (matches(entry)) { ++count; } }
        return count;
    }
private:
    std::vector<int> entries_;
    std::unique_ptr<Policy> policy_;
};

int main() {
    // Add the static_asserts above main, then print the line.
    return 0;
}
Hint 1: the idea

Traits answer questions about special members and class properties. For calls, wrap the expression in a concept so an invalid call makes the concept false instead of breaking the build.

Hint 2: a first step

template<class T> concept Recordable = requires(Ledger& ledger, T& values) { ledger.record(values); }; then static_assert(Recordable<int[3]>);.

Show one solution
Run the solution C++
#include <concepts>
#include <iostream>
#include <memory>
#include <span>
#include <string>
#include <type_traits>
#include <vector>

class Policy {
public:
    virtual ~Policy() = default;
    virtual bool allows(int entry) const = 0;
};

class Ledger {
public:
    Ledger() = default;
    Ledger(const Ledger&) = delete;
    Ledger& operator=(const Ledger&) = delete;
    Ledger(Ledger&&) = default;
    Ledger& operator=(Ledger&&) = default;
    void record(std::span<const int> values) { entries_.insert(entries_.end(), values.begin(), values.end()); }
    std::vector<int> entries() const { return entries_; }
    template<class Predicate>
    requires std::predicate<Predicate, int>
    std::size_t count_if_entry(Predicate matches) const {
        std::size_t count = 0;
        for (int entry : entries_) { if (matches(entry)) { ++count; } }
        return count;
    }
private:
    std::vector<int> entries_;
    std::unique_ptr<Policy> policy_;
};

template<class T>
concept Recordable = requires(Ledger& ledger, T& values) { ledger.record(values); };

template<class F>
concept EntryPredicate = requires(const Ledger& ledger, F f) { ledger.count_if_entry(f); };

struct ByInt { bool operator()(int entry) const { return entry > 0; } };
struct ByText { bool operator()(const std::string& text) const { return text.empty(); } };

static_assert(!std::is_copy_constructible_v<Ledger> && !std::is_copy_assignable_v<Ledger>);
static_assert(std::is_move_constructible_v<Ledger> && std::is_move_assignable_v<Ledger>);
static_assert(std::is_abstract_v<Policy> && std::has_virtual_destructor_v<Policy>);
static_assert(std::is_same_v<decltype(std::declval<const Ledger&>().entries()), std::vector<int>>);
static_assert(Recordable<std::vector<int>> && Recordable<int[3]>);
static_assert(!Recordable<std::vector<double>>);
static_assert(EntryPredicate<ByInt> && !EntryPredicate<ByText>);

int main() {
    std::cout << "Public types checked\n";
    return 0;
}
Text
Public types checked

std::vector<double> is refused because a span of const int can only view storage that really holds ints; there is no element-by-element conversion. The predicates are named structs rather than lambdas because a lambda cannot appear at namespace scope in a static_assert without an unused-variable warning. These checks pin the interface, but not behavior: a record that silently dropped every value would pass them all. The next lesson checks behavior against an independent model.

Was this article helpful?

Your response is saved on this device.