静态操作符重载模拟单位
oldrev
2007-10-14
今天我在新闻组里用砖头引出来的,呵呵:
struct Mass { private double m_value; } struct kg { static Mass opMul_r(double value) { return Mass(value); } } struct g { static Mass opMul_r(double value) { return Mass(value / 1000); } } void main() { Mass m = 100*kg; m = 1*g; } |
|
oldrev
2007-10-16
忘了说,也可以不用操作符重载实现:
const Mass kg = Mass(1); const Mass g = Mass(0.001); Mass m = 100*kg; m = 1*g; |
|
oldrev
2007-10-16
还有更变态的,用 static 操作符重载确保 struct 指针定义的正确性:
struct foo { static bool opMul(foo* x) { return true;} } void main() { foo* p; assert(foo* p); // just checking that we declared p correctly foo* null; // hey, look! null really can be an identifier } |