什么是std :: false_type或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结构?

yujunjie19860211 回答:什么是std :: false_type或std :: true_type?

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

类似地:

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表示为类型。这在类型特征中很有用,您可以根据模板参数满足的某些条件,让类模板从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,只要template参数不能满足专业化所需的所有内容(本例中为Identifier类型)。

本文链接:https://www.f2er.com/3166371.html

大家都在问