1、rank
//The rank of an array type is its number of dimensions. For other types is zero.
实现方式
通过integral_constant递归的展开数组的一个维度获取最终结果。
性能开销
模版推导过程都是在编译阶段完成,不涉及运行时开销。
调用stl内容
std integral_constant
//The rank of an array type is its number of dimensions. For other types is zero.
/// rank
template<typename>
struct rank
: public integral_constant<std::size_t, 0> { };
template<typename _Tp, std::size_t _Size>
struct rank<_Tp[_Size]>
: public integral_constant < std::size_t, 1 + rank<_Tp>::value > { };
template<typename _Tp>
struct rank<_Tp[]>
: public integral_constant < std::size_t, 1 + rank<_Tp>::value > { };
代码示例
代码源地址:http://www.cplusplus.com/reference/type_traits/rank/
// array rank example
#include <iostream>
#include <type_traits>
int main() {
std::cout << "rank:" << std::endl;
std::cout << "int: " << std::rank<int>::value << std::endl;
std::cout << "int[]: " << std::rank<int[]>::value << std::endl;
std::cout << "int[][10]: " << std::rank<int[][10]>::value << std::endl;
std::cout << "int[10][10]: " << std::rank<int[10][10]>::value << std::endl;
return 0;
}
Possible output:
rank:
int: 0
int[]: 1
int[][10]: 2
int[10][10]: 2
应用场景
The rank of an array type is its number of dimensions. For other types is zero.
2、extent
Trait class to obtain the extent of the Ith dimension of type T.
实现方式
通过integral_constant完成具体数值的获取,通过递归调用获取到相应的一个维度的值。
性能开销
模版推导过程都是在编译阶段完成,不涉及运行时开销。
调用stl内容
std integral_constant
/// extent
template<typename, unsigned _Uint>
struct extent
: public integral_constant<std::size_t, 0> { };
template<typename _Tp, unsigned _Uint, std::size_t _Size>
struct extent<_Tp[_Size], _Uint>
: public integral_constant < std::size_t,
_Uint == 0 ? _Size : extent < _Tp,
_Uint - 1 >::value >
{ };
template<typename _Tp, unsigned _Uint>
struct extent<_Tp[], _Uint>
: public integral_constant < std::size_t,
_Uint == 0 ? 0 : extent < _Tp,
_Uint - 1 >::value >
{ };
代码示例
代码源地址:http://www.cplusplus.com/reference/type_traits/extent/
// array rank/extent example
#include <iostream>
#include <type_traits>
int main() {
typedef int mytype[][24][60];
std::cout << "mytype array (int[][24][60]):" << std::endl;
std::cout << "rank: " << std::rank<mytype>::value << std::endl;
std::cout << "extent (0th dimension): " << std::extent<mytype,0>::value << std::endl;
std::cout << "extent (1st dimension): " << std::extent<mytype,1>::value << std::endl;
std::cout << "extent (2nd dimension): " << std::extent<mytype,2>::value << std::endl;
std::cout << "extent (3rd dimension): " << std::extent<mytype,3>::value << std::endl;
return 0;
}
Possible output:
mytype array (int[][24][60]):
rank: 3
extent (0th dimension): 0
extent (1st dimension): 24
extent (2nd dimension): 60
extent (3rd dimension): 0
应用场景
Trait class to obtain the extent of the Ith dimension of type T.
参考:gcc8源码