How to define opCast from native types
w0rp
devw0rp at gmail.com
Fri Feb 7 04:44:17 PST 2014
D only lets you define operator overloads in methods, unlike C++
which lets you define overloads as functions. If you want such an
operator overload, you will have to define it as a method.
However, I suggest that most of the time, writing an opCast
overload is usually the wrong solution. It's often better to
write functions for type conversions instead, which can easily be
defined outside of the struct definition and used with UFCS.
So you can have say this...
ll.toBoxedInteger
... instead of this
cast(Integer) ll
However I would suggest that even in this case converting from
long to int is error prone, so I would just force users of your
struct to cast first from long to int, then wrap the number in
your boxed struct.
Integer(cast(int) ll)
You are much more likely to get warnings from D compilers about
the cast in the right places now. However you can go one step
further and ask yourself, do you need boxed integers at all? D
allows you to create collections of primitive types and so on, so
you might not even need a boxed type like Integer, however there
may be some use cases.
More information about the Digitalmars-d
mailing list