使用可变模板函数的内置多维数组的大小

Size of built-in multidimensional array using variadic template function

本文关键字:内置 数组 函数      更新时间:2023-10-16

在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
    };
};