Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
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
Rozpustnik: 124
Data dołączenia: Jun 2019
Posty: 29
Dzięki: 72
2 tygodnie temu · 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
Rozpustnik: 112
Data dołączenia: Apr 2022
Posty: 3
Dzięki: 27
2 tygodnie temu · 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
Rozpustnik: 139
Data dołączenia: Jul 2018
Posty: 21
Dzięki: 15
2 tygodnie temu · 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.