(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)
谢谢