c++ type trait 之 useful trait

本文通过几个具体的示例介绍了C++中的模板元编程概念和技术。这些示例包括使用`rank`和`extent`来获取数组的维度,使用`remove_extent`和`remove_all_extents`去除数组类型中的维度,利用`underlying_type`获取枚举类型的底层类型,通过`decay`进行类型的衰减转换,使用`enable_if`和`conditional`进行条件类型的定义,并演示了如何通过`common_type`获取两种类型之间的通用类型。

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

#include <iostream>
#include <array>

using namespace std;
enum class color : char
{
    yellow,
    red,
    bule
};
int main()
{
    //row Array的维度
    cout << rank<int []>::value << endl;
    //extent<T,I = 0> 维度I的宽度
    cout << extent<int[5][7],1>::value << endl;
    //
    remove_extent<int[5][3]>::type a = { 5,4,3 };//int[3]
    remove_all_extents<int[5][3]>::type b = 5;//int
    underlying_type<color>::type c = 'e'; // char
    //使const int& decay(衰退为int)by value
    decay<const int&>::type i = 5;// int
    //enable_if<B,T> 若B为真则产出type T 否则产出void
    enable_if<true, double>::type d = 3.11; // value
    //conditional<B,T,D>若B为真则产出type T,否则产出 type D
    conditional<true, string, double>::type s = "Marco";// string
    //common_type<T,D> 得到类型T和类型D的共通类型
    cout << typeid(common_type<int, double>::type).name() << endl;
    //result_of<F,Args>见其他博文详细介绍
    //alignment_of<T> alignment_storage<Len>
    //alignment_storage<Len,Align>
    //alignment_union<Len,Types...>见详细博文补充
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值