Skip to content

Instantly share code, notes, and snippets.

@run-dlang
Created May 10, 2023 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save run-dlang/9b7aec72710b1108fc8277789776962a to your computer and use it in GitHub Desktop.
Save run-dlang/9b7aec72710b1108fc8277789776962a to your computer and use it in GitHub Desktop.
Code shared from run.dlang.io.
class C {
int* result;
ref T opCast(T: int*)(){
return result;
}
}
auto main() {
auto c = new C();
int y = 40;
cast(int*) c = &y;
assert(*c.result == y);
}
struct S {
int* result;
ref T opCast(T: int*)(){
return result;
}
}
auto f() {
auto s = new S();
int y = 40;
//cast(int*) s = &y; // ERROR: cast(int*) s is not an lvalue and cannot be modified
auto s2 = S();
cast(int*) s2 = &y; //now it works
//if(s2){ // ERROR: template instance opCast!bool not defined
// For classes, I guess the default implicitly bool conversion just checks for null instead of trying to call opCast!bool
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment