WooGame Blog
WooGame Blog
About
怎么理解 std::true_type, std::false_type
❓

怎么理解 std::true_type, std::false_type

Published
February 14, 2025
Author
WuZheng

个人理解

在类型推导过程中,参数和结果都是类型,而不是数值,true_type 和 false_type 即是推导过程中代表真假两种结果的类型。
在数值计算中,有 true/false 值表示真假,在类型计算中 true/false 都是 bool,需要在类型的世界中有表示真假的类型,就是 true_type 和 false_type 了。

源码

template <class _Ty, _Ty _Val> struct integral_constant { static constexpr _Ty value = _Val; using value_type = _Ty; using type = integral_constant; constexpr operator value_type() const noexcept { return value; } _NODISCARD constexpr value_type operator()() const noexcept { return value; } }; template <bool _Val> using bool_constant = integral_constant<bool, _Val>; using true_type = bool_constant<true>; using false_type = bool_constant<false>;
将模板展开,简化理解:
struct true_type { static constexpr bool value = true; constexpr operator bool() const noexcept { return true; } _NODISCARD constexpr bool operator()() const noexcept { return true; } }; struct false_type { static constexpr bool value = false; constexpr operator bool() const noexcept { return false; } _NODISCARD constexpr bool operator()() const noexcept { return false; } };
true_type 和 false_type 都是 struct,是两个类型,它们有一个 static bool 值,能表示它们实际的数值。

参考

  • Stack OverflowStack OverflowWhat is std::false_type or std::true_type?
    What is std::false_type or std::true_type?

    What is std::false_type or std::true_type?

    I saw its usage as below template &lt;typename T&gt; struct DependentFalse : std::false_type {}; Then, it is used here template &lt;typename T&gt; class RadarSensor { static_assert(

    Stack OverflowStack Overflow
 
Table of Contents
个人理解源码参考
Copyright 2026 WuZheng