Timon Gehr:

> > Similar code using user-created struct doesn't compile:
> >
> >
> > struct Foo {
> >      int* p;
> >      size_t n;
> > }
> > void main() {
> >      Foo f;
> >      auto x = cast(int*)f; // compile error here
> > }
> >
> 
> That is not similar code. This is:
> 
> struct Foo {
>      size_t length;
>      int* ptr;
>      T opCast(T: int*)(){return ptr;}
> }
> 
> void main() {
>      Foo f;
>      auto x = cast(int*)f; // no compile error here
> }

I see. The bug report of mine asks to remove that opCast() then :-)


> extern(C) void foo(char* str);
> foo(cast(char*)"hello");

cast(char*) is D code, it's not a legacy C idiom, so you are writing it now in 
the D programs. Five years from now do you prefer D programmers to write:

extern(C) void puts(const char* str);
void main() {
    puts(cast(char*)"hello");
}

Or:

extern(C) void puts(const char* str);
void main() {
    puts("hello".ptr);
}

?
Casts are unsafe and using the ptr is even shorter to write. I don't seen the 
need of that opCast.


> -1. I don't really see any point in disallowing it. It is an explicit 
> cast, not some kind of bug prone implicit behaviour.

In D there is only one syntax to perform a const cast or reinterpret cast, so D 
casts are sometimes dangerous: you change something but you forgot to update 
one cast, the compiler gives you zero warnings because casts are usually 
silently accepted, and your code breaks. This has happened to me more than one 
time in D coding. It's much better to minimize their number in the D code (and 
it's often better to write them in a smart way, with a type taken from what you 
are working on, like cast(typeof(x)), instead of specifying an explicit type 
like cast(int)).

Sometimes I am not happy even using Unqual!(), I'd like something that performs 
a more focused job, like a Deconst!() that only removes all the const/immutable 
from a type, and nothing else.

Bye,
bearophile

Reply via email to