is_union, is_class,integral_cons

2022-03-01  本文已影响0人  404Not_Found

is_union

struct A {};
union B
{
    int num;
    char type;
};

int main(int argc, char ** argv)
{

    cout << is_union<A>::value << endl;
    cout << is_union<B>::value << endl;
    return 0;
}

c++17 中:

struct A {};
union B
{
    int num;
    char type;
};

int main(int argc, char ** argv)
{

    cout << is_union_v<A> << endl;//0
    cout << is_union_v<B> << endl;//1
    return 0;
}

is_class

struct A {};
union B
{
    int num;
    char type;
};

int main(int argc, char ** argv)
{
    cout << is_class<A>::value << endl;//1
    cout << is_class<B>::value << endl;//0
    return 0;
}

integral_constant

template<class T,
    T _Val>
    struct integral_constant
{   // convenient template for integral constant types
    static constexpr T value = _Val;

    using value_type = T;
    using type = integral_constant;

    constexpr operator value_type() const noexcept
    {   // return stored value
        return (value);
    }

    _NODISCARD constexpr value_type operator()() const noexcept
    {   // return stored value
        return (value);
    }
};

int main(int argc, char **argv)
{

    cout << std::integral_constant<int, 15>::value << endl;//1
    cout << std::integral_constant<bool, true>::value << endl;//15
    return 0;
}

integral_constant 是一个包装目的的类

struct A {};
union B
{
    int num;
    char type;
};

int main(int argc, char **argv)
{

    cout << std::integral_constant<int, 15>::value << endl;//1
    cout << std::integral_constant<bool, true>::value << endl;//15

    std::integral_constant<bool, !is_union<B>::value> myobj1;
    cout << myobj1.value << endl;

    std::integral_constant<bool, !is_union<A>::value> mobj2;
    cout << mobj2.value << endl;
    return 0;
}

将 !is_union<B>::value 这个值 包装成一个类型,类型为 integral_constant<bool, !is_union<B>::value>

在很多需要类型的场合中,就可以使用这个类型。
is_union<B>::value 在编译的适合就确定了。

上一篇 下一篇

猜你喜欢

热点阅读