C++标准模板(STL)- 类型支持 (类型修改,移除给定数组类型的所有维度,std::remove_all_extents)

类型特性


类型特性定义一个编译时基于模板的结构,以查询或修改类型的属性。

试图特化定义于 <type_traits> 头文件的模板导致未定义行为,除了 std::common_type 可依照其所描述特化。

定义于<type_traits>头文件的模板可以用不完整类型实例化,除非另外有指定,尽管通常禁止以不完整类型实例化标准库模板。
 

类型修改

类型修改模板通过应用修改到模板参数,创建新类型定义。结果类型可以通过成员 typedef type 访问。
 

移除给定数组类型的所有维度

std::remove_all_extents

template< class T >
struct remove_all_extents;

(C++11 起)

T 是某类型 X 的多维数组,则提供等于 X 的成员 typedef type ,否则 typeT

成员类型

名称 定义
type T 的元素类型

辅助类型

template< class T >
using remove_all_extents_t = typename remove_all_extents<T>::type;

(C++14 起)

可能的实现

template<class T>
struct remove_all_extents { typedef T type;};
 
template<class T>
struct remove_all_extents<T[]> {
    typedef typename remove_all_extents<T>::type type;
};
 
template<class T, std::size_t N>
struct remove_all_extents<T[N]> {
    typedef typename remove_all_extents<T>::type type;
};

调用示例

#include <iostream>
#include <type_traits>
#include <typeinfo>

template<class A>
void remove_all_extents(const A&)
{
    typedef typename std::remove_all_extents<A>::type Type;
    std::cout << "underlying type: " << typeid(Type).name() << std::endl;
}

int main()
{
    float arr1[2][2][3];
    int arr2[3][2];
    float arr3[1][1][1][1][2];
    double arr4[2][3];
    uint8_t arr5[1][2][3][1];
    uint16_t arr6[1][2][3][1];
    uint32_t arr7[1][2][3][1];
    uint64_t arr8[1][2][3][1];
    long arr9[1][2][3][1];

    remove_all_extents(arr1);
    remove_all_extents(arr2);
    remove_all_extents(arr3);
    remove_all_extents(arr4);
    remove_all_extents(arr5);
    remove_all_extents(arr6);
    remove_all_extents(arr7);
    remove_all_extents(arr8);
    remove_all_extents(arr9);

    return 0;
}

输出

underlying type: f
underlying type: i
underlying type: f
underlying type: d
underlying type: h
underlying type: t
underlying type: j
underlying type: y
underlying type: l

猜你喜欢

转载自blog.csdn.net/qq_40788199/article/details/134618875