skip to content

Your numeric algorithms library's public API is built on std::enable_if; how do you decide whether, when and how to move it to C++20 concepts?

level: principalimportance: should knowfreq 30%

answer

  1. who your consumers are
  2. named requirements, readable errors
  3. a constraint change is an API change
  4. __cpp_concepts dual path
  5. pin the accepted set in tests

basics

~20 s

Move when every supported consumer builds as C++20, or keep a dual path behind __cpp_concepts. The gains are named requirements, readable errors and overloads ordered by subsumption; treat each changed constraint as an API change and pin the accepted types in compile-only tests.

solid answer

~50 s

Start from the consumers: concepts need C++20, so if the library still promises C++17 users, the choice is a C++20-only major release or a dual path selected with the `__cpp_concepts` feature-test macro, which doubles what must be tested. The benefits are real: requirements get names that appear in the declaration and in diagnostics, refinements order themselves by subsumption instead of hand-made mutually exclusive `enable_if` conditions, and the requirements become documentation. The risk is that rewriting a constraint silently changes **which types are accepted**, and callers' own SFINAE or `requires` checks against your functions change with it. So the migration is an API change: write compile-only tests that pin the accepted and rejected types before touching anything, convert the internal helpers first, and change public signatures in one planned release. Avoid over-constraining with exact `std::same_as` checks where convertibility is what the algorithm needs.

code

cpp · 18 lines
cpp
#include <iostream>
#include <type_traits>
#include <vector>

#if defined(__cpp_concepts) && __cpp_concepts >= 201907L
#include <concepts>
template <class T> concept Number = std::integral<T> || std::floating_point<T>;
template <Number T>
#else
template <class T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0>
#endif
double mean(const std::vector<T>& v) {
    double s = 0;
    for (T x : v) s += x;
    return v.empty() ? 0.0 : s / v.size();
}

int main() { std::cout << mean(std::vector<int>{1, 2, 4}) << '\n'; }

go deeper

for a junior

Know that concepts are C++20-only and that code using them cannot be compiled as C++17.

for a middle

Show how the same requirement looks as an enable_if condition and as a concept, and how a feature-test macro selects between them.

for a senior

Spot where a rewritten constraint changes the accepted set, and write compile-only tests that pin accepted and rejected types before migrating.

for a principal

Choose between a C++20-only major release, a dual path and internal-first adoption from the consumers' standard modes and upgrade plans, and own the deprecation trigger for the old path.

## The decision in one line Moving a public template API from `std::enable_if` to C++20 constraints is worth it when the library can rely on C++20 for its consumers or can afford a dual path, and when the team treats the change as an API revision rather than a refactor. There is no single right answer; the deciding factors are who builds against the library and how much churn they will accept. ## What concepts buy | Concern | `enable_if` (C++11/14/17) | Concepts (C++20) | |---|---|---| | Where the requirement lives | buried in a template parameter or return type | named, in the declaration | | Diagnostic on misuse | a list of ignored candidates with raw trait text | the failing concept and the failing part | | Refined overloads | hand-made mutually exclusive conditions | ordered automatically by subsumption | | Reuse | copy the trait expression | name the concept once | | Documentation | prose next to the code | the concept itself | For a numeric algorithms library, the diagnostics alone change the support load: `constraints not satisfied ... does not satisfy 'Number'` is something a user can act on. ## What it costs - **A language floor.** Concepts require C++20. Every consumer of the public headers must compile in that mode. - **Signature changes.** Constraints are part of a template's declaration, so two declarations with different constraints declare different templates. Users who wrote explicit specializations or explicit instantiations of your function templates, or who spelled the hidden `enable_if` template argument explicitly, may need edits. - **A changed accepted set.** A concept rarely reproduces an old `enable_if` condition exactly. `std::integral<bool>` is true, for example, so a hand-written `is_arithmetic_v<T> && !is_same_v<T, bool>` condition and a `std::integral`-based concept disagree about `bool`. - **Downstream detection.** Callers' own SFINAE or `requires` probes of your functions answer differently when your constraints change. - **Two code paths** if you keep C++17 support, each needing tests. ## Questions a lead answers first 1. Which standard modes do supported consumers build with, and when can C++17 be dropped? 2. Is this a header-only library, or does it ship explicit instantiations in a binary whose symbols would change? 3. Which public templates have overload sets whose conditions must be mutually exclusive today, and would benefit most from subsumption? 4. Are the current requirements written down anywhere other than in `enable_if` conditions? 5. What is the release vehicle: a minor release with a dual path, or a major release that raises the floor? ## Migration strategies - **C++20-only major release.** Simplest code and the cleanest diagnostics; right when consumers already build as C++20. - **Dual path behind `__cpp_concepts`.** `#if defined(__cpp_concepts)` selects concept declarations, `#else` keeps `enable_if`. Keep both conditions provably identical and test both modes in CI; schedule the removal of the old path with a trigger, such as the last C++17 consumer upgrading. - **Concepts internally first.** Define the concept hierarchy (`Number`, `Exact`) and use it inside implementation helpers while public signatures stay unchanged; this proves the definitions before they become API. ## Guardrails - **Pin the accepted set before changing anything.** Compile-only tests built from requires-expressions, such as `template <class T> concept MeanAccepts = requires (const std::vector<T>& v) { mean(v); };` with `static_assert(MeanAccepts<int> && !MeanAccepts<std::string>);`, record today's behaviour and catch drift. - **Prefer convertibility to exact types** in public constraints unless the algorithm truly depends on the exact type; `std::same_as` rejects reasonable callers. - **Document semantic requirements.** Concepts check syntax; if the algorithm needs, say, an associative `+`, say so, because a type that satisfies but does not model the requirement is the caller's bug. - **Keep the hierarchy shallow** and build every refinement from an existing concept, so users can write their own more constrained overloads on top. ## A plan for the numeric library Inventory the public templates and their conditions; write the accepted/rejected tests; define the concepts and check they reproduce the tests in C++20 mode; ship the dual path in a minor release with `__cpp_concepts`; announce the C++17 removal, tied to the consumers' upgrade rather than a date; then delete the `enable_if` branch in the next major release.

  • Why is tightening a constraint on an existing public function template a breaking change even when it only rejects bad types?
    Code that compiled before may stop compiling, or overload resolution may pick a different function, because a candidate that used to be viable no longer is. Callers that probe your function with their own SFINAE or `requires` checks also get a different answer. Each change to the accepted set needs the same review and release notes as any other API change.
  • How do you keep the C++17 and C++20 paths of a dual-path declaration in agreement?
    Write the compile-only acceptance tests in a form both modes can run, such as `static_assert` on a detection trait, and build the test suite in both `-std=c++17` and `-std=c++20` in CI. Any type on which the two paths disagree then fails one of the two builds instead of reaching a user.

  • Replacing enable_if with a concept is a pure refactor with no effect on callers.
  • A concept-based API can still be consumed from C++17 translation units.
  • Exact std::same_as checks are always the safest public constraints.
  • Concepts verify an algorithm's semantic requirements, so documentation becomes unnecessary.
  • Checking __cplusplus >= 201703L is enough to know concepts are available.

Assumes C++20 concepts as the target and C++17 enable_if as the starting point; the __cpp_concepts macro is defined by C++20 compilers.