C++ tricks
1. 当一个文件里面代码过多时,往往需要将代码分组,C#里面有#pragma region的控制字,而C++里面缺少这个,可以使用下面这个来替代。
1 /* 2 #if decl_region || your_code_block_desc 3 your code block 4 #endif 5 */ 6 #define decl_region 1
2.预处理时计算数组大小
1 template<typename T, long N> 2 char (&ArraySizeHelper(T (&array)[N]))[N]; 3 4 #define ARRAY_SIZE(array) ((unsigned int)sizeof(ArraySizeHelper(array)))
3.属性
1 struct Rect { 2 union 3 { 4 struct { 5 int x1, y1, x2, y2; 6 }; 7 struct h 8 { 9 void operator = (int v) 10 { 11 Rect* super = (Rect*)(((char*)this) - offsetof(Rect, h));; 12 super->y2 = super->y1 + v; 13 } 14 operator int ()const 15 { 16 Rect* super = (Rect*)(((char*)this) - offsetof(Rect, h));; 17 return super->y2 - super->y1; 18 } 19 }h; 20 }; 21 };
使用时就可以像C#一样了
1 Rect r; 2 r.x1 = 10; 3 r.h = 20; 4 int h = r.h; 5 int x2 = r.x2;