| jerry 發(fā)表于 2008-5-15 15:06:00 | //關(guān)于模擬sizeof函數實(shí)現計算類(lèi)型大小 //查了很多資料,也用過(guò)模板 //但都無(wú)法獲得對象的類(lèi)型 //下面是一個(gè)用宏來(lái)實(shí)現的方法 #define my_sizeof(L_Value) ( \ (char *)(&L_Value + 1) - (char *)&L_Value \ )
#i nclude <stdio.h> #i nclude <stdio.h> int main(void){ int i; double f; double a[4]; double *p;
printf("%d\n", my_sizeof(i)); printf("%d\n", my_sizeof(f)); printf("%d\n", my_sizeof(a)); printf("%d\n", my_sizeof(p)); printf("%d\n", my_sizeof("abdegh"));
return 0; }
//模板的類(lèi)型操作 #i nclude<iostream>
using namespace std;
template<class Any> int LengthOfArray(Any * p) { return int(p+1) - int(p); }
int main() { double * q; char a[10];
cout << LengthOfArray(q)<<endl; cout << LengthOfArray(&a)<<endl; return 0; } | |