使用可变模板函数的内置多维数组的大小
Size of built-in multidimensional array using variadic template function
在c++ 11中,可以使用constexpr创建一个函数,在编译时返回内置一维数组的大小(元素数量)。在下面的例子:
template <typename T, std::size_t N>
constexpr std::size_t size(T (&array)[N])
{
return N;
}
相对于ARRAY_SIZE和类似的宏来说,这是一个更好的选择。
但是,这将只返回内置多维数组的最高有效维度的大小。
我使用以下函数来确定内置二维数组的大小:template <typename T, std::size_t N, std::size_t N2>
constexpr std::size_t size(T (&array)[N][N2])
{
return N * N2;
}
理想情况下,有一个函数返回具有任意维数的内置数组的大小是非常有用的。我认为可变模板可能会有所帮助,但我看不到解压缩模板参数的方法,因为只有一个参数传递。这样的函数可能存在吗?
#include <type_traits>
#include <cstdlib>
template <typename T>
constexpr size_t size(const T&) noexcept
{
return sizeof(T)/sizeof(typename std::remove_all_extents<T>::type);
}
的例子:
#include <cstdio>
int main()
{
int a[3][4][7][12];
char f[6];
printf("%lu == %ld ?n", size(a), 3*4*7*12);
printf("%lu == %ld ?n", size(f), 6);
return 0;
}
template<typename T> constexpr int size(T const&) {
return 1;
}
template<typename T, int N> constexpr int size(T const (&a)[N]) {
return N * size(a[0]);
}
您要找的是std::extent
。c++ 11§20.9.5:
template <class T, unsigned I = 0> struct extent;
如果T不是数组类型,或者它的秩小于等于I,或者如果I为0且T的类型为"U的未知界数组",则0;否则为T的第I维的界(8.3.4),其中I的索引是从零开始的。
用法,同样来自标准,根据需要在extent
前加上std::
:
assert((extent<int[2][4], 1>::value) == 4);
您可能也应该使用它来替换您的自定义size
函数。
编辑:哎呀,现在我读到问题的最后:vP。您还需要std::remove_extent
。
template< typename multi_array, bool = std::is_array< multi_array >::value >
struct total_extent;
template< typename multi_array >
struct total_extent< multi_array, false > {
enum { value = 1 };
};
template< typename multi_array >
struct total_extent< multi_array, true > {
enum {
value = std::extent< multi_array >::value
* total_extent< typename std::remove_extent< multi_array >
::type >::value
};
};
相关文章:
- 函数内的数组
- C++内联数组成员统一初始化
- 变量未在此范围内声明 数组线性搜索
- 如何在给定的间隔内更改数组的值
- SFML访问std::vector内的数组
- 内建数组出现不允许的类型不完整错误
- 在 c++ 中直接访问的内联数组声明
- C++ 如何在给定范围内将数组中的数字相加?
- const(但不是constexpr)用作内置数组大小
- 如何在 c/c++ 中访问结构内的数组
- 如何在结构C++初始化内置数组
- 内置数组初始化,没有 constexpr 大小
- new[] 是否初始化内置数组
- 分配器和 C++ 中内置数组之间的区别
- 数组模板和内置数组类型之间有区别吗
- 为什么内置数组不安全?
- 内置数组的大小是什么类型?
- 将内置数组替换为std/tr1/boost::数组是否总是安全的?
- 开始和结束函数用于内置数组类型
- 在访问多维数组的内置数组和初始化器列表时交换标识符和下标