22. SFINAE gate
In a low-latency encoder, you must avoid accidental serialization of complex types. Gate APIs at compile time to prevent slow, unsafe code paths while keeping the hot path monomorphic.
struct Fill { int id; double px; };
template<class T>
constexpr std::enable_if_t<std::is_trivially_copyable_v<T>, size_t>
wire_size(const T&) noexcept { return sizeof(T); }
template<class T>
constexpr std::enable_if_t<!std::is_trivially_copyable_v<T>, size_t>
wire_size(const T&) = delete;
Part 1.
For calls to wire_size(v), explain which overload participates for trivially copyable vs non-trivially copyable T, and why one case fails to compile.
Part 2.
(1) Where does SFINAE apply here, and which overloads get discarded?
(2) Return-type vs parameter vs template-parameter enable_if: selection and diagnostics differences?
(3) Would C++20 requires change semantics here, or mainly improve clarity?
(4) Does noexcept impact overload resolution or only code generation in this case?
(5) Code-size risks from many SFINAE overloads on hot paths?
Answer
Answer (Part 1)
If T is trivially copyable, the first template’s enable_if_t<true, size_t> succeeds, so that overload is viable and selected. If T is not trivially copyable, the first template is removed by SFINAE; the second template becomes viable but is deleted, causing a hard compile-time error at the call site.
Answer (Part 2)
(1) SFINAE happens substituting the return type’s enable_if_t. When the condition is false, that overload is discarded from the set.
(2) Return-type SFINAE doesn’t aid partial ordering and can hurt diagnostics. Parameter or template-parameter enable_if generally yields clearer ranking and errors.
(3) requires expresses the same constraint declaratively. It improves readability and diagnostics without changing the intended selection behavior.
(4) noexcept does not rank overloads here. It can still improve codegen by enabling no-throw assumptions and reducing EH metadata.
(5) Each constrained overload can instantiate per T, inflating binary and I-cache pressure. Prefer one constrained template or concepts to consolidate.