opCast fails when this is null.

Mike Wey mike-wey at example.com
Sat Oct 28 13:24:49 UTC 2017


The following code runs correctly when compiled with ldc (1.4.0) but 
fails with an assert error when compiled with dmd (2.076 and ldc 1.2.0)


```
class A
{

}

class B
{
	T opCast(T)()
	{
		return this;
	}
}

void main()
{
	A a = null;
	B b = null;

	auto c = cast(Object)a;
	auto d = cast(Object)b; // Fails with: 
core.exception.AssertError at test.d(8): null this
}
```

How would you write an opCast that would handle this case correctly?

Testing if this is null at the start of the opCast doesn't help since 
the assert is thrown before that happens.
Making the opCast static leaves us without access to this, which would 
be needed in my use case.
We can't relay on ufcs since the rewrite to opCast doesn't happen when 
it's not a member function.

-- 
Mike Wey


More information about the Digitalmars-d-learn mailing list