Skip to content

Read and Test Compile-Time Failures

The Course
•
35 min study

An interface makes two kinds of promise. It promises to accept some uses: an Engine can be moved, count_events takes a predicate over const Event&. It also promises to refuse others: an Engine cannot be copied, and a callable that takes an int cannot be passed as an event predicate. Runtime tests can only exercise the first kind, because a refused use never becomes a program. If a later change accidentally adds a copy constructor or loosens a constraint, every runtime test still passes, and the refusal you relied on is gone.

So refusals need their own tests, run by the compiler. A compile-pass test proves that intended usage is accepted. A compile-fail test proves that a specific forbidden usage is rejected, and for the right reason. This lesson shows both, and how to read the diagnostics they produce.

Predict and run

Predict before running C++
#include <iostream>
#include <concepts>

inline constexpr auto positive = [](int value) { return value > 0; };

int main() {
    static_assert(std::predicate<decltype(positive),int>);
    std::cout << positive(3) << "\n";
    return 0;
}
Check your prediction
Text
1

The static_assert ran while compiling, before the program existed. If it had been false, there would be no program to run. assert(positive(3)) is a different kind of evidence: it checks one value on one run. A static_assert checks a property of a type, so it holds for every value and every run, but it says nothing about what the function returns. Good test suites need both kinds.

Testing that a call is refused, inside a passing build

You cannot write static_assert(!compiles(count_matching(values, wrong))) directly: outside a template, an invalid expression is simply an error. Inside a concept, though, an invalid expression in a requires expression just makes the concept false. Wrap the call in a concept and you can assert that it is rejected, in a file that itself compiles:

Compile-time tests of a template's interface C++
#include <concepts>
#include <iostream>
#include <span>
#include <string>

template<class Predicate>
requires std::predicate<Predicate, const int&>
std::size_t count_matching(std::span<const int> values, Predicate matches) {
    std::size_t count = 0;
    for (const int& value : values) { if (matches(value)) { ++count; } }
    return count;
}

template<class F>
concept Countable = requires(std::span<const int> values, F f) { count_matching(values, f); };

inline constexpr auto by_int = [](int n) { return n > 0; };
inline constexpr auto by_text = [](const std::string& s) { return s.empty(); };
inline constexpr auto no_result = [](int) {};

static_assert(Countable<decltype(by_int)>);
static_assert(!Countable<decltype(by_text)>);
static_assert(!Countable<decltype(no_result)>);

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

The three assertions say: an int predicate is accepted, a string predicate is refused, and a callable that returns nothing is refused, because void is not boolean-testable. Delete the requires line from count_matching and recompile. The second and third assertions now fail, because without a constraint the call expression looks valid from outside; the error would only appear when the body is instantiated. That is the loosened-constraint regression, caught by the build. The lambdas are inline constexpr because unused namespace-scope variables would trigger a warning under this course's flags.

Compile-fail files

Concept-wrapped checks are precise but indirect. The project also keeps two small programs that must not compile, written the way a real consumer would write the mistake:

  • reject_copy.cpp copies an Engine.
  • reject_predicate.cpp passes [](int) { return true; } to count_events.

Compiled separately with -fsyntax-only, each must fail, and the error must mention the intended cause:

Shell
$ c++ -std=c++20 -fsyntax-only reject_copy.cpp
reject_copy.cpp:3:38: error: call to deleted constructor of 'Engine'
./engine.h:46:5: note: 'Engine' has been explicitly marked deleted here
$ c++ -std=c++20 -fsyntax-only reject_predicate.cpp
reject_predicate.cpp:5:17: error: no matching function for call to 'count_events'
./engine.h:61:13: note: candidate template ignored: constraints not satisfied

The course checker looks for a marker word in each, deleted and count_events, rather than the full message, because wording differs between compilers and versions. Matching a marker matters: a compile-fail test that accepts any failure would also pass when engine.h is missing or has a syntax error, proving nothing.

That is also why the checker first compiles compile_contracts.cpp, a valid consumer that includes the same header. If the valid consumer fails, the environment is broken and the negative results mean nothing. A negative test is only evidence after a positive one has shown the setup works.

Reading a long template error

Template diagnostics can run for dozens of lines. Read them in this order:

  1. The first error: line, which names the failing expression and its location in your file.
  2. candidate template ignored notes, which list each overload that was considered and why it was rejected.
  3. because ... evaluated to false notes, which walk down through nested concepts. The last one is usually the concrete reason.

Skip lines inside standard library headers until those steps leave you stuck. With constrained templates, the useful part is near the top; with unconstrained ones, it is often buried, which is one more argument for concepts.

Practice

Exercise

Your turn

Write a compile-time contract suite for a move-only Engine stand-in and the count_matching template above. Define class Engine holding a std::vector<std::unique_ptr<int>>, declare its copy operations deleted and its move operations defaulted, as the project's header does, and assert that it is not copy constructible, not copy assignable, move constructible and move assignable. Then assert, through a Countable concept, that an int predicate is accepted and that a predicate taking const std::string& and one returning void are refused. When everything compiles, print:

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

int main() {
    // Write the Engine class, count_matching, Countable and the static_asserts.
    std::cout << "Type contracts checked\n";
    return 0;
}
Hint 1: the idea

Type traits from <type_traits> answer questions about special member functions. A concept wrapping a call answers questions about a template's constraint.

Hint 2: a first step

Start with static_assert(!std::is_copy_constructible_v<Engine>); and static_assert(std::is_move_assignable_v<Engine>);, then copy the Countable concept from the lesson.

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

class Engine {
public:
    Engine() = default;
    Engine(const Engine&) = delete;
    Engine& operator=(const Engine&) = delete;
    Engine(Engine&&) = default;
    Engine& operator=(Engine&&) = default;
private:
    std::vector<std::unique_ptr<int>> rules_;
};

static_assert(!std::is_copy_constructible_v<Engine>);
static_assert(!std::is_copy_assignable_v<Engine>);
static_assert(std::is_move_constructible_v<Engine>);
static_assert(std::is_move_assignable_v<Engine>);

template<class Predicate>
requires std::predicate<Predicate, const int&>
std::size_t count_matching(std::span<const int> values, Predicate matches) {
    std::size_t count = 0;
    for (const int& value : values) { if (matches(value)) { ++count; } }
    return count;
}

template<class F>
concept Countable = requires(std::span<const int> values, F f) { count_matching(values, f); };

int main() {
    auto by_int = [](int n) { return n > 0; };
    auto by_text = [](const std::string& s) { return s.empty(); };
    auto no_result = [](int) {};
    static_assert(Countable<decltype(by_int)>);
    static_assert(!Countable<decltype(by_text)>);
    static_assert(!Countable<decltype(no_result)>);
    std::cout << "Type contracts checked\n";
    return 0;
}
Text
Type contracts checked

Why delete the copy operations by hand when a unique_ptr cannot be copied anyway? Remove the four declarations and the first static_assert fails. std::vector declares its copy constructor for every element type, so std::is_copy_constructible_v<std::vector<std::unique_ptr<int>>> is true, and so is the trait for a class holding one. An actual copy would still fail, but only deep inside the vector's code. Type traits see declarations, not whether the body could compile, so the explicit = delete is what makes the refusal visible to traits, to concepts and to readers. The checkpoint next combines a constrained helper with runtime behavior tests.

Was this article helpful?

Your response is saved on this device.