Project Elvis

bauss jj_1337 at live.dk
Sun Oct 29 20:37:21 UTC 2017


On Sunday, 29 October 2017 at 20:15:41 UTC, Ola Fosheim Grøstad 
wrote:
> On Sunday, 29 October 2017 at 20:05:08 UTC, Steven 
> Schveighoffer wrote:
>> It's actually perfect for generic code. If you need something 
>> other than the current "0 means false" behavior (like for 
>> instance int), then you wrap in a type that opCast!bool means 
>> what you want.
>
> I think we just have to agree that we disagree. Generic 
> programming relies on consistent protocols.
>
> So, you generally don't want 0 to be considered as an invalid 
> value. Because of the defaults in D, cast(bool) isn't really 
> all that useful.
>
> It would have been better if the default was to deny casting to 
> bool, but that is too late as D has decided to be too close to 
> C on so many levels, so it would be a bad idea to diverge from 
> C for that now. So the next best thing is to let the programmer 
> specify that something is invalid with some other means than 
> opCast to bool.
>
> *shrug*

But casting to bool is what you use to tell whether something is 
valid or not.

true = valid, false = invalid.

If you want 0 to be valid for a type then you wrap around it with 
opCast.

Ex.

---
import std.stdio;

struct MyInt
{
	int value;
	
	bool opCast(T : bool)()
	{
		return value >= 0;
	}
}

void main()
{
	MyInt a = MyInt(1);
	MyInt b = MyInt(0);
	MyInt c = MyInt(-1);
	
	if (a) writeln("a is valid");
	if (b) writeln("b is valid");
	if (c) writeln("c is valid");
}
---

Output:
a is valid
b is valid


More information about the Digitalmars-d mailing list