Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::void_t — detecting valid types

std::void_t from <type_traits> maps any valid pack of type arguments to void. Combined with SFINAE, it can detect whether a nested type is available without making the entire program ill-formed.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

template<class...> using void_t = void; // namespace std; header <type_traits>

std::void_t is an alias template declared in <type_traits>. For any number of valid type arguments, it denotes void: both std::void_t<> and std::void_t<int, double> are that same type. It is neither a function nor a Boolean-valued trait; it provides no separate ::type or ::value member.

Its usefulness comes from template argument substitution. In the example, typename T::value_type must name a type. If it does, std::void_t<typename T::value_type> produces void, so the partial specialization of has_value_type matches and inherits from std::true_type. Otherwise, substitution fails in the immediate context, SFINAE discards that specialization, and the primary template supplies std::false_type.

std::void_t accepts types, not arbitrary expressions. To test an expression, its type can be supplied through decltype(...). This technique checks syntactic and type validity, not computed results or runtime behavior. It does not suppress every error: invalid use outside a SFINAE context and errors caused by incidental instantiation can still prevent compilation.

Examples

#include <iostream>
#include <type_traits>

template<class T, class = void>
struct has_value_type : std::false_type {};

template<class T>
struct has_value_type<T, std::void_t<typename T::value_type>>
    : std::true_type {};

struct Item {
    using value_type = int;
};

static_assert(std::is_same_v<std::void_t<>, void>);
static_assert(std::is_same_v<std::void_t<int, double>, void>);
static_assert(has_value_type<Item>::value);
static_assert(!has_value_type<int>::value);

int main() {
    std::cout << std::boolalpha
              << has_value_type<Item>::value << '\n'
              << has_value_type<int>::value << '\n';
}

Result

true
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources