方法一:宏定义
#include<iostream> using namespace std; #define LengthOf(Value) (char*)(&Value+1)-(char*)&Value int main() { int i; double d; double *q; char a[10]; printf("%d\n",LengthOf(i)); //printf("%d\n",sizeof(i)); printf("%d\n",LengthOf(d)); printf("%d\n",LengthOf(q)); printf("%d\n",LengthOf(a)); return 0; }结果:4 8 4 10
方法二:template
#include<iostream> using namespace std; template <class Any> int LengthOf(Any *p) { return int(p+1)-int(p); } int main() { int *i; double *d; char a[10]; printf("%d\n",LengthOf(i)); //printf("%d\n",sizeof(i)); printf("%d\n",LengthOf(d)); printf("%d\n",LengthOf(&a)); }结果:4 8 10