Thoughts on some code breakage with 2.074

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu May 11 16:52:53 PDT 2017


On Thu, May 11, 2017 at 07:46:24PM -0400, Steven Schveighoffer via Digitalmars-d wrote:
[...]
> But this still doesn't mean that *all* bool conversions are value
> based. In at least the struct and class cases, more than just the bits
> are checked.
[...]

Wait, what?  You can use a *struct* as a bool condition?!

I tried this:

	import std.stdio;
	struct S {}
	void main() {
		S s;
		if (s) { writeln("WAT"); }
	}

But the compiler (rightly) said:

	test.d(5): Error: expression s of type S does not have a boolean value

Or were you talking about structs that define opCast!bool? (In which
case it's certainly intentional and doesn't pose a problem.)

I can see classes being usable in conditions, though, since they're
essentially pointers hiding behind an abstraction. Still, it doesn't
quite sit right with me. For example:

	class C { }
	class D { bool opCast(T : bool)() { return false; } }
	void main() {
		C c;
		D d = new D;

		if (!c) { ... }		// OK, expected semantics
		if (!d) { ... }		// *** What happens here?
	}

Whereas had the last two lines been written:

		if (c is null) { ... }
		if (d is null) { ... }

the intent would be much clearer. (And of course, d would be usable
without "is null" if you actually intended to invoke opCast!bool.)


T

-- 
In a world without fences, who needs Windows and Gates? -- Christian Surchi


More information about the Digitalmars-d mailing list