关于 vs2019 c++20 规范里的 STL 库里模板 decay_t<T>

(1) 这个模板,在库代码里非常常见。 decay 英文是“衰弱,消减” 的意思,大概能感觉到就是要简化模板参数 T 的类型,去掉其上的修饰符。因为常用且复杂,故单独列出其源码和注释。先举例其应用场景:

在这里插入图片描述

以下给出 decay_t 的源码:

在这里插入图片描述

以及:

在这里插入图片描述

以及:

在这里插入图片描述

以及:

在这里插入图片描述

(2)以下给出对 decay_t 的测试,保证总结的结论是正确的:

在这里插入图片描述

(3) 再补充一例当给 function 传递的是可调用对象,而非函数时,decay 对模板参数的影响

在这里插入图片描述

(4) 给出其源码注释,看起来也不是太直观:

template <class _Ty>  // determines decayed version of _Ty 确定_Ty的衰变版本
struct decay
{
    /*
    template <class _Ty>
    struct remove_reference { using type = _Ty; };

    template <class _Ty>
    struct remove_reference<_Ty&> {	using type = _Ty; };

    template <class _Ty>
    struct remove_reference<_Ty&&> { using type = _Ty; };

    template <class _Ty>
    using remove_reference_t = typename remove_reference<_Ty>::type;
    */
    using _Ty1 = remove_reference_t<_Ty>;
    /*
    template <class _Ty, class = void> // add pointer (pointer type cannot be formed)
    struct _Add_pointer
    { using type = _Ty; };

    template <class _Ty>   // (pointer type can be formed)
    struct _Add_pointer<_Ty, void_t<remove_reference_t<_Ty>*>>
    { using type = remove_reference_t<_Ty>*; };

    template <class _Ty>
    struct add_pointer
    { using type = typename _Add_pointer<_Ty>::type; };

    template <class _Ty>
    using add_pointer_t = typename _Add_pointer<_Ty>::type;
    */
    // 经测试 is_function_v<less<int>()> = true ,证明对象函数,也是函数
    using _Ty2 = typename _Select<is_function_v<_Ty1>>::template _Apply<add_pointer<_Ty1>, remove_cv<_Ty1>>;
    /*
    // Select between aliases that extract either their first or second parameter
    // 在提取第一个或第二个参数的别名之间进行选择
    template <bool>
    struct _Select
    {
        template <class _Ty1, class>
        using _Apply = _Ty1;
    };

    template <>
    struct _Select<false>
    {
        template <class, class _Ty2>
        using _Apply = _Ty2;
    };
    */
    using type = typename _Select<is_array_v<_Ty1>>::template _Apply<add_pointer<remove_extent_t<_Ty1>>, _Ty2>::type;
    // 经过细致冗长的推导,type 应该等于 _Ty* , 意思是指向函数的指针 ,而_Ty = less<int>()
};

template <class _Ty>
using decay_t = typename decay<_Ty>::type;

(5)

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值