Bug 9249 – Defining opCast disables downcasting and explicit upcasting
Status
RESOLVED
Resolution
INVALID
Severity
blocker
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-01-01T08:20:42Z
Last change time
2022-02-14T12:57:40Z
Assigned to
No Owner
Creator
Puneet Goel
Comments
Comment #0 by puneet — 2013-01-01T08:20:42Z
This becomes blocking now since opCast is required for implementing toImpl.
test.d(13): Error: template instance opCast!(Foo) does not match template declaration opCast(T) if (is(T == string))
class Bar { // 1
public T opCast(T)() // 2
if(is(T == string)) // 3
{ // 4
return "Bar"; // 5
} // 6
} // 7
// 8
class Foo: Bar { } // 9
// 10
void main() { // 11
Bar bar = new Foo(); // 12
Foo foo = cast(Foo) bar; // 13
} // 14
Comment #1 by andrej.mitrovich — 2013-01-10T20:40:57Z
What your sample is showing is downcasting, this is upcasting:
class C1
{
public T opCast(T)()
if (is(T == string))
{
return "C1";
}
}
class C2 : C1
{
}
void main()
{
C2 c2;
C1 c1 = cast(C1)c2;
}
Both fail though.
Comment #2 by puneet — 2013-01-10T20:54:39Z
Yup, my bad. I have updated the summary as per Andrej's comment.
Comment #3 by andrej.mitrovich — 2013-01-10T20:58:23Z
I've tried a version as old as 2.032 which has the same behavior. It's odd this wasn't picked up before.
What I think should happen is opCast should be tried first, and if it can't be instantiated try to do the regular upcast/downcast.
Comment #4 by acehreli — 2015-03-18T14:12:48Z
*** Issue 14298 has been marked as a duplicate of this issue. ***
Comment #5 by razvan.nitu1305 — 2022-02-14T12:57:40Z
I don't think this issues is valid. Typically, when defining an overload operator all uses of that operator are redirected to the overload. That is what happens in both of the provided examples (upcasting and downcasting). As for the example of upcasting, one simply needs to avoid the explicit cast to make it work.
This is all according to the spec and consistent across the other overloaded operators.
Closing as invalid. Please reopen if I am missing something.