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

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

我看到它的用法如下

template <typename T>
struct DependentFalse : std::false_type
{};

那么,这里就用到了

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

我不知道它有什么用?

什么是 DependentFalse 结构?

std::false_type 用作类型特征的构建块,定义为 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
};

同样:

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
};

用于将 falsetrue表示为类型。这在类型特征中很有用,您可以让 class 模板从 std::false_typestd::true_type 继承不同的(部分)特化,具体取决于模板参数满足的某些条件。这样做允许测试给定类型是否满足类型特征的条件,并通过访问静态 value 成员来获得指示结果的编译时间常量 value继承自 std::false_typestd::true_type 或通过使用转换运算符转换类型特征的实例来替代。

你在这里展示的是一个简单的类型特征,它总是(对于所有 T)求值为 std::false_type。它用在 static_asserts 中,当它们所在的模板被实例化时应该总是失败。这是必要的,因为不依赖于模板参数的 static_assert 已经在定义点触发,而不是实例化点,因此使每个包含 static_assert(false); 之类的程序格式错误.

DependentFalse 可能是 Identifier 的特化,可能如下所示:

 template<class ... Args>
 class  DependentFalse<Identifier<Args...>> : public std::true_type {}

这确保您无法编译 RadarSensor,只要模板参数不满足专业化所需的任何内容(在本例中为标识符类型)。