Created
March 7, 2022 15:45
-
-
Save pbackus/b87005c851f30dcd7693a2ae0e0afa84 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Ref(T) | |
{ | |
T* ptr; | |
ref inout(T) deref() inout | |
{ | |
return *ptr; | |
} | |
alias deref this; | |
} | |
Ref!T byRef(T)(return ref T lvalue) | |
{ | |
return Ref!T(&lvalue); | |
} | |
auto forward(T)(return auto ref T value) | |
{ | |
static if (__traits(isRef, value)) | |
return value.byRef; | |
else | |
return value; | |
} | |
// Can't escape a reference to a local | |
unittest | |
{ | |
assert(!__traits(compiles, { | |
int n = 123; | |
return n.byRef; | |
})); | |
} | |
// Can modify through a reference | |
unittest | |
{ | |
static void modify(Ref!int r) | |
{ | |
r++; | |
} | |
int n = 123; | |
modify(n.byRef); | |
assert(n == 124); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment