Thread overview
opCast + dtor error
Dec 28, 2021
vit
Dec 29, 2021
Tejas
Dec 29, 2021
vit
December 28, 2021

Hi, why this code doesn't compile?

struct Foo{
    bool opCast(T : bool)()const{
        assert(0);
    }

    ~this(){}
}

struct Bar{
    const Foo foo;
}

void main(){


}

Error: template instance opCast!(Foo) does not match template declaration opCast(T : bool)()

December 29, 2021

On Tuesday, 28 December 2021 at 18:27:36 UTC, vit wrote:

>

Hi, why this code doesn't compile?

struct Foo{
    bool opCast(T : bool)()const{
        assert(0);
    }

    ~this(){}
}

struct Bar{
    const Foo foo;
}

void main(){


}

Error: template instance opCast!(Foo) does not match template declaration opCast(T : bool)()

Since a destructor ignores const, I think adding the ~this to Foo manually is somehow making the compiler have to actually cast away const, which it is doing via cast(Foo) foo, which fails since you've declared your own opCast that only accepts arguments implicitly convertible to bool.

I say this because removing the specialisation in opCast and changing the return type of it to Foo works :

struct Foo{
    Foo opCast(T)()const {
        assert(0);
        return this;
    }
    ~this() {}

}

struct Bar{
    const Foo foo;

}

void main(){
    //Bar bar = Bar(); //this will trigger the assertion failure


}
December 29, 2021

On Wednesday, 29 December 2021 at 01:00:53 UTC, Tejas wrote:

>

On Tuesday, 28 December 2021 at 18:27:36 UTC, vit wrote:

>

[...]

Since a destructor ignores const, I think adding the ~this to Foo manually is somehow making the compiler have to actually cast away const, which it is doing via cast(Foo) foo, which fails since you've declared your own opCast that only accepts arguments implicitly convertible to bool.

I say this because removing the specialisation in opCast and changing the return type of it to Foo works :

struct Foo{
    Foo opCast(T)()const {
        assert(0);
        return this;
    }
    ~this() {}

}

struct Bar{
    const Foo foo;

}

void main(){
    //Bar bar = Bar(); //this will trigger the assertion failure


}

Thanks, you are right, generated Bar.~this() try use opCast to cast const away.
Is look like bug in compiler.

I stop using opCast for now.