什么是std :: false_type或std :: true_type?

Ton*_*ker 1 c++ c++-standard-library c++11

我看到它的用法如下

template <typename T>
struct DependentFalse : std::false_type
{};
Run Code Online (Sandbox Code Playgroud)

然后,在这里使用

template <typename T>
class RadarSensor
{
    static_assert(DependentFalse<T>::value, "RadarSensor must be created using Identifier template");
};
Run Code Online (Sandbox Code Playgroud)

我不知道它的用途是什么?

什么是DependentFalse结构?

wal*_*nut 5

std::false_type用作traits类型的构建块,并定义为std::integral_constant<bool, false>(我将在此处跳过)。它的定义可以归结为如下所示(简化):

struct false_type {
    static constexpr bool value = false;
    constexpr operator bool() const noexcept { return value; }
    // There is more here, but it doesn't really matter for your question
};
Run Code Online (Sandbox Code Playgroud)

类似地:

struct true_type {
    static constexpr bool value = true;
    constexpr operator bool() const noexcept { return value; }
    // There is more here, but it doesn't really matter for your question
};
Run Code Online (Sandbox Code Playgroud)

它被用来表示 falsetrue作为类型。这在类型特征中很有用,您可以根据模板参数满足的某些条件,让类模板继承std::false_type或继承std::true_type不同的(部分)专业化知识。这样做允许测试给定类型是否满足类型特征的条件,并获得编译时常数值,该指示通过访问静态value成员的结果,该静态成员是通过继承std::false_type或继承自std::true_type该类型的实例而替代的使用转换运算符的特征。

您在这里显示的是一个简单的类型特征,该特征总是(对所有人而言T)求和std::false_type。用于static_asserts实例化模板所在的模板时,它总是会失败。这是必需的,因为static_assert不依赖模板参数的a已在定义点而不是实例点被触发,因此使每个程序都包含static_assert(false);格式错误的内容。