Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I saw its usage as below

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

Then, it is used here

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

I do not have idea what is it used for?

What is DependentFalse structure?

like image 848
TonyParker Avatar asked Nov 04 '19 13:11

TonyParker


People also ask

What is std:: integral_ constant?

std::integral_constant wraps a static constant of specified type. It is the base class for the C++ type traits. The behavior of a program that adds specializations for integral_constant is undefined.

What is true Type C++?

What is boolean in C++? A boolean data type in C++ is defined using the keyword bool . Usually, 1 ( true ) and 2 ( false ) are assigned to boolean variables as their default numerical values.


Video Answer


1 Answers

std::false_type is used as a building block in type traits and is defined as std::integral_constant<bool, false> (which I will skip over here). It's definition boils down to something like this (simplified):

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

Similarly:

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

It is used to represent the values false and true as types. This is useful in type traits where you let a class template inherit from either std::false_type or std::true_type for different (partial) specializations, depending on some condition met by the template argument. Doing so allows one to test whether a given type satisfies the condition of the type trait and to obtain a compile time constant value indicating the result through access to the static value member which is inherited from either std::false_type or std::true_type or alternative through conversion of an instance of the type trait using the conversion operator.

What you are showing here is a simple type trait which always (for all T) evaluates to std::false_type. It is used in static_asserts that should always fail when the template they are located in is instantiated. This is necessary, because a static_assert that does not dependent on a template parameter is triggered already at the point of definition, rather than the point of instantiation, therefore making every program containing something like static_assert(false); ill-formed.

like image 169
walnut Avatar answered Oct 08 '22 14:10

walnut