3 ms·
I think it’s less a problem with explicit casts and more a problem of insufficient expressivity. If what you wanted was “cast to the type of b”, then something
by aw1621107 5y ago
I think it’s less a problem with explicit casts and more a problem of insufficient expressivity. If what you wanted was “cast to the type of b”, then something along the lines of C++’s decltype would be better:
b = static_cast<decltype(b)>(a);
And as other commenters have pointed out, if implicit widening is disallowed that would also prevent the potential bug.
- astrange 5y agoThe problem with mandating this is that it doesn't really express anything - the semantics are the same as `b = a;`. And there's a cost because it's quite verbose. If what you want to express is "I know b and a have different storage sizes", that could be useful, but it doesn't do that because eg if you typo `b` for `a`, then `b = static_cast<decltype(b)>(b);` is still accepted.
- aw1621107 5y ago> The problem with mandating this is that it doesn't really express anything - the semantics are the same as `b = a;`. And there's a cost because it's quite verbose. Sure, but at least the problem is back to "should conversions/casts be implicit or explicit?", rather than "I cannot do what I want with explicit casts". > If what you want to express is "I know b and a have different storage sizes" You may not even know this (e.g., in generic code), and if you did want to ensure different storage sizes specifically, then you want a (static) assert. > eg if you typo `b` for `a`, then `b = static_cast<decltype(b)>(b);` is still accepted. That would also apply to the version with implicit casts/conversions, wouldn't it?