On 03/17/2015 12:14 AM, Meta wrote:

> On Tuesday, 17 March 2015 at 05:32:49 UTC, Ali Çehreli wrote:
>> On 03/16/2015 04:59 PM, Lukasz Wrzosek wrote:
>>> Bug reported as
>>> https://issues.dlang.org/show_bug.cgi?id=14298
>>
>> Thanks...
>>
>> I have carried the discussion over to the main newsgroup:
>>
>>   http://forum.dlang.org/thread/me8e0a$1kp6$1...@digitalmars.com
>>
>> As I mention there, there is a workaround: Add a catch-all opCast to
>> the class in question, which can simply forward to the all-powerful
>> std.conv.to:
>>
>>     T opCast(T)()
>>     {
>>         import std.conv;
>>         return this.to!T;
>>     }
>>
>> Now it compiles and works as expected.
>>
>> Ali
>
> That will throw an exception if the conversion can't be done instead of
> just returning null, won't it?

You are right. I did not think it through but we can add template constraints to make it impossible to throw. (Still, we shouldn't need to do that for a cast to base types.)

> Why can't you do this instead?
>
> t opCast(t)()
> if (is(typeof(cast(T)this)))
> {
>      return cast(T)this;
> }

That has the same problem: 'cast(T)this' happens to be an explicit cast, which is disabled by the opCast overload for int.

Ali

Reply via email to