类型特性
类型特性定义一个编译时基于模板的结构,以查询或修改类型的属性。
试图特化定义于 <type_traits> 头文件的模板导致未定义行为,除了 std::common_type 可依照其所描述特化。
定义于<type_traits>头文件的模板可以用不完整类型实例化,除非另外有指定,尽管通常禁止以不完整类型实例化标准库模板。
类型修改
类型修改模板通过应用修改到模板参数,创建新类型定义。结果类型可以通过成员 typedef type 访问。
从给定数组类型移除一个维度
std::remove_extent
template< class T > | (C++11 起) |
若 T
是某类型 X
的数组,则提供等于 X
的成员 typedef type
,否则 type
为 T
。注意若 T 是多维数组,则只移除第一维。
成员类型
类型 | 定义 |
type | T 的元素类型 |
辅助类型
template< class T > | (C++14 起) |
可能的实现
template<class T>
struct remove_extent { typedef T type; };template<class T>
struct remove_extent<T[]> { typedef T type; };template<class T, std::size_t N>
struct remove_extent<T[N]> { typedef T type; };
调用示例
#include <iostream>
#include <iterator>
#include <algorithm>
#include <type_traits>//std::rank(C++11)获取数组类型的维数
//std::extent(C++11)获取数组类型在指定维度的大小template<class A>
typename std::enable_if< std::rank<A>::value == 1 >::type
print_1d(const A& a)
{std::copy(a, a + std::extent<A>::value,std::ostream_iterator<typename std::remove_extent<A>::type>(std::cout, " "));std::cout << std::endl;
}int main()
{int a[][5] = {{1, 2, 3, 7, 8}, {4, 5, 6, 9, 0}};// print_1d(a); // 编译时错误print_1d(a[0]);print_1d(a[1]);std::cout << std::endl;char str[][5] = {{'a', 'b', 'c', 'd', 'f'}, {'h', 'i', 'j', 'k', 'l'}};print_1d(str[0]);print_1d(str[1]);std::cout << std::endl;return 0;
}
输出
1 2 3 7 8
4 5 6 9 0a b c d f
h i j k l