求传入函数中的数组长度

 摘自: http://blog.chinaunix.net/u2/75321/showart_1161698.html
 
一般来说数组传入函数里面后会退化为指针,sizeof则没有用了,所以一般都要多传入一个数组长度。但是还是有办法求长度的。
下面三个方法的原理都是利用array-size函数把数组的长度骗取 出来,而且利用&号过滤
指针.
template <int N>
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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值