A request: templated opCast() signature for class/struct
Pragma
ericanderton at yahoo.removeme.com
Fri Feb 16 12:59:29 PST 2007
Walter, All,
I know this has been bandied about before, but I think it warrants some serious attention. Heck, I even argued
against it before, until I saw what was really needed (My apologies, Sean).
The problem, for the uninitiated, is that D cannot overload by return type. This leaves exactly one possible signature
for any given struct or class, should one need to implement opCast(). This yields the following problems:
- Can only cast() to one explicit type other than the given type of the enclosing struct/class
- D does not recognize a templated opCast() signature as mapped to implicit or explicit casts
- Behaves non-uniformly when compared to other operator overloads (we can template other operators just fine)
- Doesn't fit to most use-cases: you rarely want to map to be able to cast to just one other type
- Is a blocker for implementing anything resembling duck typing.
I'd like to propose the following behaviors for the use of an templated opCast() signature:
- Map "T opCast(T)()" to the same class of operations and situations as "T opCast()"
- Still allow the traditional "T opCast()" signature.
This comes along with the following ideas and implications that I'm not sure of:
- Does opCast() even map to implicit casts at all? Maybe it should in some cases?
- DMD could map T opCast(T)() to implicit cast() for non-scalar types (can this mess with inheritance?)
As far as making this jive with existing code, I would expect DMD to simply try the explicit signature with T as the
return type, and failing that, try matching the templated signature. This would all be in place of the current opCast()
method match check in the semantic pass.
AFAIK, DMD will not let you overload templates by return type anyway, so the programmer is left to pick one opCast()
style over the other. That is to say, one cannot have "bool opCast()" and "T opCast(T)()" in the same class/struct at
present. So this presents no additional obstacles for developers, aside from the meta-programming chops needed to
support multiple results for casting.
(The current motivation, aside from countless other posts, for this idea is here:
http://www.dsource.org/projects/tango/forums/topic/12)
--
- EricAnderton at yahoo
More information about the Digitalmars-d
mailing list