I’m learning D and have seen a lot of code like this:
ushort x = to!ushort(args[1]);
I assume this casts args[1] to ushort, but what’s the difference between this and cast(ushort)?
EDIT: And what other uses does the exclamation mark operator have?
In D,
is shorthand for the template instantiation
and is similar to
in languages like C++/Java/C#.
The exclamation point is to note the fact that it’s not a regular argument, but a template argument.
The notation does not use angle brackets because those are ridiculously difficult to parse correctly for a compiler (they make the grammar very context-sensitive), which makes it that much more difficult to implement a correct compiler. See here for more info.
The only other use I know about is just the unary ‘not’ operation (e.g.
false == !true)… I can’t think of any other uses at the moment.Regarding the cast:
cast(ushort)is an unchecked cast, so it won’t throw an exception if the value is out of range.to!ushort()is a checked cast, so it throws an exception if the value is out of range.