dmd 1.057 and 2.041 release

bearophile bearophileHUGS at lycos.com
Mon Mar 8 06:38:42 PST 2010


Ary Borenszweig:
> I'm normally interested to enter the if branch if x is not null and it 
> has an interesting value. For example, if I implement a String class I 
> would implement it as not being empty. But I think the biggest problem 
> is making a different semantic for this to structs and classes. You'll 
> have programmers wondering why the if branch was entered even if my 
> class implemented opBool not to enter it. But time will tell.

A solution can be to disallow opCast!(bool) in classes. So when in your code you convert a struct (that already defines opCast!(bool)) to a class, or when you try to add opCast!(bool) to a class, the compiler gives you a nice compilation error, and saves you from possible bugs.
A warning too can be better than nothing.


> For opCast maybe it would be better to have some examples, like:
> 
> T opCast(T)() if (is(T == bool)) {
> }
> 
> T opCast(T)() if (is(T == int)) {
> }
> 
> (it's not very intuitive that I have to do that to implement opCast, 
> it's different from the other operator overloading that rely on strings)

This works:

import std.stdio: writeln;

struct Foo {
    int len;

    this(int x) {
        this.len = x;
    }

    T opCast(T:bool)() {
        return this.len != 0;
    }
    T opCast(T:int)() {
        return this.len;
    }
}

void main() {
    auto f = Foo(5);

    if (f)
        writeln("true");
    else
        writeln("false");

    writeln(cast(int)f);
}

Bye,
bearophile


More information about the Digitalmars-d-announce mailing list