cast overly permissive with extern(C++ ) classes; should cast through `void*`

timotheecour timothee.cour2 at gmail.com
Tue Feb 6 21:34:07 UTC 2018


On Tuesday, 6 February 2018 at 21:13:50 UTC, timotheecour wrote:
> On Tuesday, 6 February 2018 at 20:39:09 UTC, Timothee Cour 
> wrote:
>> should we force force casting through `void*` for extern(C++) 
>> classes ?
>> i.e. `cast(Derived) cast(void*) base_instance;`
>>
>> currently, `cast(A) unrelad_cpp_instance` happily compiles but 
>> shouldn't, it's very error prone even though the cast syntax 
>> suggests type safety; especially a problem if we make a class 
>> become extern(C++) in the future
>>
>> [came up after discussing with jacob-carlborg]
>


Actually how about introducing a library solution for explicit 
casting:
* works with UFCS chains (unlike cast)
* DSL is very intuitive, readable and extensible

```
foo.Cast!"+immutable,dynamic"
myint.cast!"-const,"unsigned"
```

meaning: +immutable: make immutable; -const: remove const storage 
class if was const; dynamic: only allow dynamic cast (cf avoids 
above bug); unsigned: cast integer to unsigned; other keywords 
could be trivially added to DSL


alternative is not DRY (eg: `Foo foo; cast(const(Foo)) foo;` ; 
not typesafe/expressive: (cast(Foo)foo) will remove const-ness in 
foo even though just a dynamic cast was intended for eg; and 
doesn't work in UFCS chains (requires lots of parenthesis)



More information about the Digitalmars-d mailing list