struct size{
static const int cnt = N;
};
template <typename T, int N>
size <N> array_size(T (&a)[N]);
#define dimensionof(x) array_size(x).cnt
typedef unsigned char byte_t;
template <int N>
struct size_v1{
byte_t c[N];
};
template <typename T, int N>
size <N> array_size_v1(T (&a)[N]);
#define dimensionof_v1(x) sizeof(array_size(x).c)
template <typename T, int N>
byte_t (&dimen(T (&a)[N]) )[N];
#define dimmensionof_v2(x) sizeof(dimen(x))
更简单的实现
template <int N>
struct SIZE{
static const int cnt = N;
};
template <typename T, int N>
int arr_size(T (&arr)[N]){
/*
cout << sizeof(arr) / sizeof(T) << endl;//work well
struct SIZE <N> s;//also work well
cout << s.cnt << endl;
*/
return SIZE <N> ::cnt;
}
本文介绍了一种使用C++模板元编程技巧来获取数组长度的方法。通过定义模板结构体和特例化,可以在不传递数组长度的情况下准确地获取到数组的实际大小。这种方法避免了手动传递长度参数的不便,适用于各种需要知道数组大小的场景。
2681

被折叠的 条评论
为什么被折叠?



