digitalmars.D.learn - cast expressions
Sometimes I'm unsure what exactly is the difference between a) cast(t)x b) (t)x c) t(x) I know, (c) is a constructor call, but for basic types that's the same as (a) isn't it? If t provides a constructor for typeof(x) and x provides opCast to type t, which one is called? Does it depend on the form (a), (b), or (c)? Does all three forms work if only the constructor or only the opCast is provided? And is (b) always equivalent to (a)? (there is an odd example in the grammar where this is not the case)
May 03 2023
On Wednesday, 3 May 2023 at 09:03:38 UTC, Dom DiSc wrote:I know, (c) is a constructor call, but for basic types that's the same as (a) isn't it?No, a cast allows for overflow `cast(ubyte) 256`, while the constructor needs an integer that fits. `ubyte(256)` is an error.If t provides a constructor for typeof(x) and x provides opCast to type t, which one is called?When casting, opCast has precedence over a constructor.Does all three forms work if only the constructor or only the opCast is provided?A constructor call will not be lowered to opCast, but a cast can be lowered to a constructor call.And is (b) always equivalent to (a)?C style cast syntax is not allowed in D.
May 03 2023