skip to content

A C++ to_string overload names a helper struct's nested type in its return type, and an unsupported argument causes a hard error instead of SFINAE; why?

level: seniorimportance: should knowfreq 35%

answer

  1. where the failure happened
  2. immediate context only
  3. separately instantiated helper
  4. make the helper SFINAE-friendly

basics

~20 s

SFINAE covers only the immediate context: the types and expressions written in the signature. Naming the helper's nested type instantiates the helper class, and an error inside that class's definition happens in a separate instantiation, so it is fatal.

solid answer

~40 s

The standard allows soft failure only for invalid types and expressions in the **immediate context** of the signature. In `typename str_result<T>::type label(const T&, int)`, substitution names `str_result<Opaque>::type`, which forces the class template `str_result<Opaque>` to be instantiated. If its definition contains `using type = decltype(std::declval<const T&>().str());`, the invalid expression sits inside the class definition, a separately instantiated construct, so it is a hard error even though overload resolution triggered it. Apple clang 21 shows this as `no member named 'str' in 'Opaque'` with notes `in instantiation of template class 'str_result<Opaque>' requested here` and `while substituting deduced template arguments`. The fix is to make the helper SFINAE-friendly: declare `type` only in a partial specialization keyed on `std::void_t`, so a bad `T` yields a helper with no `type`, which fails softly in the signature.

code

cpp · 21 lines
cpp
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>

struct Money { std::string str() const { return "12.50 EUR"; } };
struct Opaque {};

// SFINAE-friendly helper: 'type' exists only when t.str() is valid.
template <class T, class = void>
struct str_result {};
template <class T>
struct str_result<T, std::void_t<decltype(std::declval<const T&>().str())>> {
    using type = decltype(std::declval<const T&>().str());
};

template <class T>
typename str_result<T>::type label(const T& t, int) { return t.str(); }
std::string label(...) { return "<opaque>"; }

int main() { std::cout << label(Money{}, 0) << ' ' << label(Opaque{}, 0) << '\n'; }

go deeper

for a junior

Remember that SFINAE only forgives problems in the function's declaration, not in other code the compiler has to generate along the way.

for a middle

Explain that naming a member of a class template instantiates the class, and that errors inside that definition are not substitution failures.

for a senior

Read the instantiation note chain, find the construct outside the immediate context, and restructure helpers so the failing case has no member rather than an invalid one.

for a principal

Set expectations for library traits: every trait used in signatures must be SFINAE-friendly, and reviews should reject helpers that hard-error on unsupported types.

## The immediate context SFINAE is narrower than "anything that goes wrong during overload resolution". The standard says invalid types and expressions cause deduction failure **only in the immediate context** of the places being substituted (the function type, the template parameter declarations, the `explicit` specifier, a partial specialization's argument list). It then excludes **separately instantiated constructs**, and adds a note that effects of substitution, such as instantiating a class template specialization or implicitly defining a function, are not in the immediate context and can make the program ill-formed. The standard's own example shows the line: ```cpp template <class T> struct A { using X = typename T::X; }; template <class T> typename T::X f(typename A<T>::X); template <class T> void f(...) { } f<int>(0); // OK: substituting the return type fails softly first ``` and for `g`, whose parameter type `A<int>::X` is substituted before anything else fails, `g<int>(0)` is an error because `A<int>` must be instantiated and its body is invalid. ## The to_string case A pre-C++20 utility library factors the return type into a helper: ```cpp template <class T> struct str_result { using type = decltype(std::declval<const T&>().str()); }; template <class T> typename str_result<T>::type label(const T& t, int) { return t.str(); } std::string label(...) { return "<opaque>"; } ``` Calling `label(Opaque{}, 0)` deduces `T = Opaque` and substitutes into the return type. To know what `str_result<Opaque>::type` is, the compiler instantiates `str_result<Opaque>`. The invalid `.str()` lives inside that class's definition, which is outside the immediate context, so the build stops. Apple clang 21 (`-std=c++17`) prints: ```plaintext error: no member named 'str' in 'Opaque' note: in instantiation of template class 'str_result<Opaque>' requested here note: while substituting deduced template arguments into function template 'label' [with T = Opaque] ``` The second and third lines are the signature of this problem: the error is in a helper, reached while substituting. ## Other sources of hard errors during overload resolution - **Helper class templates** whose definitions are invalid for the argument, as above, including a `static_assert` inside a trait. - **Deduced `auto` return types.** Nothing in the signature is invalid, so the template can be selected; the body must then be instantiated to deduce the type, and errors there are fatal. - **The `noexcept` specifier.** It is excluded from substitution during deduction and only instantiated when needed, at which point an invalid expression makes the program ill-formed. - **Implicitly defined special members** that substitution happens to require, for example a defaulted copy constructor that is ill-formed for the type. - **Function bodies**, always, including the body of a lambda appearing in the signature. ## Making a helper SFINAE-friendly Move the risky expression into a partial specialization, so an unsupported `T` gets a helper with **no `type` member** instead of an invalid one: ```cpp template <class T, class = void> struct str_result {}; // no 'type' at all template <class T> struct str_result<T, std::void_t<decltype(std::declval<const T&>().str())>> { using type = decltype(std::declval<const T&>().str()); }; ``` Now `str_result<Opaque>` instantiates cleanly as an empty struct, and naming `str_result<Opaque>::type` in `label`'s return type is an invalid type in the immediate context, a soft failure. The fallback `label(...)` is chosen. This is exactly why the standard specifies traits such as `std::enable_if`, `std::common_type` and `std::underlying_type` as having **no member `type`** in the failing case rather than an invalid one. ## Order matters too Substitution proceeds in **lexical order** and stops at the first failure. That is why the standard's `f` above is fine: its leading return type `typename T::X` fails softly before the parameter type `A<T>::X` is ever substituted, so `A<int>` is never instantiated. The same declaration written with a trailing return type puts the parameter first, and the hard error appears. Two practical consequences follow: - put the cheapest, most likely-to-fail check **first** in the declaration, so a doomed candidate is rejected before it can trigger expensive or fatal instantiations; - declaring one function template twice with checks that would trigger instantiations in a different order is ill-formed, no diagnostic required, so keep redeclarations textually identical. ## A diagnostic routine When a SFINAE overload set produces an error instead of falling through: 1. Read the notes bottom-up. `while substituting deduced template arguments` means the failure came from overload resolution. 2. Look for `in instantiation of template class ... requested here` between the error and that note; that names the construct that is outside the immediate context. 3. Either rewrite that construct to have no member in the failing case, or spell the expression directly in the signature with `decltype`.

  • Why is an invalid expression in a noexcept specifier not a substitution failure?
    The standard leaves the `noexcept` specifier out of the function type it substitutes during deduction. It is instantiated only when it is needed, for example when the function is called or its exception specification is queried, and an invalid expression at that point makes the program ill-formed instead of removing the overload.
  • How can you tell from a clang diagnostic that an error came from outside the immediate context?
    The error points into some other template's definition, and the note chain includes `in instantiation of template class '...' requested here` followed by `while substituting deduced template arguments into function template`. That chain means substitution caused a separate instantiation, and the error occurred inside it, where SFINAE does not reach.

  • Any error that occurs during overload resolution counts as a substitution failure.
  • A static_assert inside a helper trait quietly removes the overload.
  • Deduced auto return types take part in SFINAE like decltype return types.
  • When the helper's instantiation fails, the compiler moves on to the next overload.
  • Wrapping the helper's type in std::conditional_t makes the failure soft.