C++

Lesson 07

Template constraints

Use concepts or focused type requirements so template errors point to the contract the caller missed.

Good Code

src/review_score.cpp
#include <concepts>

template <typename T>
concept ScoredReview = requires(const T& value) {
    { value.score() } -> std::convertible_to<int>;
};

template <ScoredReview T>
bool passes_review_threshold(const T& review)
{
    // Concept names the API expected from T.
    return review.score() >= 70;
}

Bad Code

review_score.cpp
template <typename T>
bool passes_review_threshold(T review)
{
    // Unconstrained template errors appear far from the call site.
    return review.score() >= 70;
}

Review Notes

What to review

Good Code

The good version defines a concept that says the type must expose score() convertible to int. Failed calls point to that named contract.

Bad Code

The bad version accepts any type until the function body asks for score(). The compiler error can be long and detached from the API intent.

Takeaways

  • Template code should name the operations it needs, because unconstrained templates fail far from the call site.