Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
Discussion

How to write zero-overhead Type Traits using std::void_t and SFINAE in C++17 [StackOverflow Architecture Guide]

modern_cpp_artisan
C++ Template Wizard
MEMBER
Vertreter: 124
Beitrittsdatum: Jun 2019
Beiträge: 29
Danke: 72
Vor 2 Wochen · Aug 6, 2026 2:40 PM
#1

Detecting whether a class has a specific member function at compile-time:

CPP
template<typename T, typename = void>
struct has_serialize : std::false_type {};

template<typename T>
struct has_serialize<T, std::void_t<decltype(std::declval<T>().Serialize())>> : std::true_type {};

// Usage
static_assert(has_serialize<MyPacket>::value, "MyPacket must implement Serialize()");

std::void_t maps any valid type expression to void. If T.Serialize() is invalid, SFINAE drops the specialization cleanly without compiler errors!

variant_visitor_pro
Type-Safe C++
MEMBER
Vertreter: 112
Beitrittsdatum: Apr 2022
Beiträge: 3
Danke: 27
Vor 2 Wochen · Aug 6, 2026 5:31 PM
#2

std::void_t made writing custom type traits so much simpler in C++17 compared to the old sizeof trick.

llvm_compiler_dev
LLVM & Clang Hacker
MEMBER
Vertreter: 139
Beitrittsdatum: Jul 2018
Beiträge: 21
Danke: 15
Vor 2 Wochen · Aug 7, 2026 5:35 AM
#3

C++20 concepts superseded void_t for new code, but understanding void_t is vital for maintaining existing high-performance libraries.