std::decay结合cppreference理解

文章详细解析了C++中的`std::decay`模板以及类型转换规则,特别关注了函数指针和数组的特殊处理,通过示例展示了`is_decay_equ`和类型转换的等价性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <type_traits>
#include "stdio.h"
template<typename T, typename U>
constexpr bool is_decay_equ = std::is_same_v<std::decay_t<T>, U>;
int func(float num) {return num;}
struct S
{
    void f_ref() & {}
    void f_const() const {}
};
int main()
{
    static_assert
    (
        is_decay_equ<int, int> &&
        ! is_decay_equ<int, float> &&
        is_decay_equ<int&, int> &&
        is_decay_equ<int&&, int> &&
        is_decay_equ<const int&, int> &&
        is_decay_equ<int[2], int*> &&
        ! is_decay_equ<int[4][2], int*> &&
        ! is_decay_equ<int[4][2], int**> &&
        is_decay_equ<int[4][2], int(*)[2]> &&
        is_decay_equ<int(int), int(*)(int)>
    );
    printf("1 %s\n",is_decay_equ<int[4][2], int(*)[2]>?"true":"false");
    printf("2 %s\n",is_decay_equ<int(int), int(*)(int)>?"true":"false");
/**
 * https://en.cppreference.com/w/cpp/types/decay 
 * template< class T >
struct decay;
 * Performs the type conversions equivalent to the ones performed when passing function arguments by value. Formally:

1) If T is "array of U" or reference to it, the member typedef type is U*.
2) Otherwise, if T is a function type F or reference to one?, the member typedef type is std::add_pointer<F>::type.
3) Otherwise, the member typedef type is std::remove_cv<std::remove_reference<T>::type>::type.
*/
    printf("3 %s\n",is_decay_equ<int(float),std::add_pointer_t<int(float)>>?"true":"false");  // true
    typedef int(*funcRef)(float);
    printf("4 %s\n",std::is_same_v<funcRef,std::add_pointer_t<int(float)>>?"true":"false");   // true,对应3)
    printf("5 %s\n",std::is_same_v<funcRef,int(*)(float)>?"true":"false");   // true,对应3)
    printf("6 %s\n",std::is_same_v<funcRef,int(float)>?"true":"false");   // false
    //int(*funcRef)(float)&;
    //funcRef = = func;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值