How does the std::void_t idiom detect whether a C++ type has a str() member, and why must the primary template's second parameter default to void?
answer
- primary false, specialization true
- declval inside decltype
- any valid type list becomes void
- the default must equal void
basics
~20 sA partial specialization takes std::void_t<decltype(std::declval<const T&>().str())> as its second argument: if the expression is valid it becomes void, matches the primary's default, and the true specialization wins; otherwise it drops out. Any other default never matches.
solid answer
~40 sThe idiom has two parts. The primary template `template <class T, class = void> struct has_str : std::false_type {};` answers no. A partial specialization `has_str<T, std::void_t<decltype(std::declval<const T&>().str())>> : std::true_type {}` answers yes. When you write `has_str<Money>`, the second argument is the default, `void`. The compiler then tries the specialization: if `str()` is valid, `void_t<...>` collapses to `void`, the arguments match, and the more specialized `true_type` version is used; if it is invalid, substitution into the specialization's argument list fails and only the primary remains. If the default were `int`, `has_str<Money>` would mean `has_str<Money, int>`, which `void` never matches, so the trait is always false. `std::void_t` is C++17; the result is then fed to tag dispatch or `if constexpr`.
code
cpp · 29 lines#include <iostream>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
// Primary template: the second parameter defaults to void.
template <class T, class = void>
struct has_str : std::false_type {};
// Partial specialization: well-formed only when t.str() is.
template <class T>
struct has_str<T, std::void_t<decltype(std::declval<const T&>().str())>>
: std::true_type {};
struct Money { std::string str() const { return "12.50 EUR"; } };
template <class T>
std::string to_string_impl(const T& t, std::true_type) { return t.str(); }
template <class T>
std::string to_string_impl(const T&, std::false_type) { return "<opaque>"; }
template <class T>
std::string to_string(const T& t) { return to_string_impl(t, has_str<T>{}); }
int main() {
static_assert(has_str<Money>::value && !has_str<int>::value);
std::cout << to_string(Money{}) << ' ' << to_string(42) << '\n';
}go deeper
Recognise the shape of a detection trait: a false primary template and a true partial specialization keyed on void_t.
Explain why declval is used, what void_t collapses to, and how the primary's default argument takes part in matching.
Diagnose a trait that is always false, account for const-ness and access, and combine the trait with tag dispatch or if constexpr without instantiating invalid code.
Weigh hand-rolled detection traits against requires-expressions once the codebase can assume C++20, and decide which traits a shared library should expose.
## The parts of the idiom The detection idiom answers a yes/no question about a type, here "does `t.str()` compile for a `const T&`?", without ever calling anything. It is assembled from four standard pieces: - **`std::declval<const T&>()`** (`<utility>`) pretends to produce a value of type `const T&` in an unevaluated operand. It needs no constructor, so it works for types that cannot be default-constructed; it is ill-formed if ever evaluated. - **`decltype(expr)`** asks for the type of an expression without evaluating it. Inside a template, an invalid expression there is a substitution failure. - **`std::void_t<Ts...>`** (C++17, `<type_traits>`) is declared as `template <class...> using void_t = void;`. Whatever valid types you pass, the result is `void`; its only job is to make substitution happen. - **`std::true_type` / `std::false_type`** carry the answer as a `static constexpr bool value`. ```cpp template <class T, class = void> struct has_str : std::false_type {}; template <class T> struct has_str<T, std::void_t<decltype(std::declval<const T&>().str())>> : std::true_type {}; ``` ## How matching works When code names `has_str<Money>`: 1. The template argument list is completed from the primary template's defaults, giving `has_str<Money, void>`. 2. The compiler checks whether a **partial specialization** matches. It substitutes `Money` into the specialization's argument list, which forms `decltype(std::declval<const Money&>().str())`. 3. If that expression is valid, `void_t<...>` is `void`, the specialization's arguments are `<Money, void>`, they equal the requested arguments, and the specialization (deriving from `true_type`) is selected. 4. If the expression is invalid, substitution into the partial specialization's argument list fails. That list is one of the places where failure is soft, so the specialization simply does not match and the primary template, `false_type`, is used. ## Why the default must be void The specialization can only ever produce `void` as its second argument. The user never writes the second argument, so what is requested is always the **primary's default**. They must agree: - default `void`: valid expression gives `<T, void>` against requested `<T, void>`, a match; - default `int`: valid expression gives `<T, void>` against requested `<T, int>`, never a match. With `class = int` the trait is silently `false` for every type. Apple clang 21 then reports the consequence elsewhere, for example `static assertion failed due to requirement 'has_str<Money, int>::value'`, which is a useful clue when you see the hidden second argument in the message. ## Using the answer: tag dispatch The classic C++11/14 consumer is **tag dispatch**: overload a helper on `std::true_type` and `std::false_type` and pass the trait object as an argument. ```cpp template <class T> std::string to_string_impl(const T& t, std::true_type) { return t.str(); } template <class T> std::string to_string_impl(const T&, std::false_type) { return "<opaque>"; } template <class T> std::string to_string(const T& t) { return to_string_impl(t, has_str<T>{}); } ``` Only the selected helper's body is instantiated, so `t.str()` is never compiled for a type without it. C++17 code can branch with `if constexpr (has_str<T>::value)` instead. ## Pitfalls - **Const-ness and value category matter.** `std::declval<T>()` is an rvalue `T`; a `str()` qualified `&` would be missed. Probe the form your code will actually call, usually `const T&`. - **Access is checked.** Access checking is part of substitution, so a **private** `str()` is reported as absent when the trait is used outside the class. - **Validity only.** The trait proves the expression compiles, not that it returns something sensible; add `std::is_convertible` on the `decltype` if the return type matters. - **Before C++17** you write your own `void_t`. Early wording left it unclear whether unused alias template arguments were substituted at all; the standard now says a dependent alias template-id still undergoes substitution, which is what makes the one-line alias reliable. ## Detection options compared | Technique | Where the probe lives | Answer usable as | |---|---|---| | Expression SFINAE on each overload | `decltype` in every overload's signature | only by overload resolution | | `void_t` trait | one partial specialization | a `bool` constant: `static_assert`, tag dispatch, `if constexpr` | | C++20 requires-expression | a `requires` block | a `bool` constant, or directly as a constraint | A named trait is worth writing when more than one place asks the same question: the probe is spelled once, and each consumer reads `has_str<T>::value`. C++20 lets you write the same test as `requires (const T& t) { t.str(); }`, which is covered with constraints and requires-expressions.
- How do you detect a member function that takes arguments, such as write(std::ostream&)?Put the arguments into the probed expression with `std::declval` as well: `std::void_t<decltype(std::declval<const T&>().write(std::declval<std::ostream&>()))>`. The specialization matches only when a call with an lvalue `std::ostream` compiles, including through default arguments or an overload that accepts it by conversion.
- How do you also require that str() returns something convertible to std::string?Keep the same specialization but derive it from `std::is_convertible<decltype(std::declval<const T&>().str()), std::string>` instead of `std::true_type`. The specialization still matches whenever `str()` is callable, and the base class then answers whether the result converts to `std::string`.
A plug adapter that only fits one socket shape: whatever the device, a working adapter always presents the same socket, void, so the wall outlet, the primary's default, must be that shape or nothing ever plugs in.
- std::void_t evaluates its argument expression and returns its type.
- The primary template's default argument can be any type, such as int.
- Detection calls str() at compile time to see whether it works.
- A private str() member makes the detection trait report true.
- std::void_t is available in every C++11 standard library.