Last active
December 19, 2015 10:19
-
-
Save tom-tan/5939244 to your computer and use it in GitHub Desktop.
Library implementation of T& in C++
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
#!/usr/bin/env rdmd | |
/** | |
* Library implementation of T& in C++ | |
* i.e. Its value can be modified | |
* but its address cannot be modified. | |
**/ | |
struct Ref(T) | |
{ | |
@system this(ref T ptr) pure nothrow | |
{ | |
payload = &ptr; | |
} | |
@safe{ | |
auto opEquals(in T rhs) const pure nothrow | |
{ | |
return *payload == rhs; | |
} | |
auto opCmp(in T rhs) const pure nothrow | |
{ | |
return *payload-rhs; | |
} | |
auto opAssign(T rhs) pure nothrow | |
{ | |
return *payload = rhs; | |
} | |
auto opUnary(string s)() pure nothrow | |
if (s == "-" || s == "+" || s == "++" || s == "--") | |
{ | |
return mixin(s~"(*payload)"); | |
} | |
auto opBinary(string s)(in T rhs) const pure nothrow | |
if (s == "+" || s == "-" || s == "*" || s == "/") | |
{ | |
return mixin("(*payload)" ~ s ~ "rhs"); | |
} | |
auto opOpAssign(string s)(in T rhs) pure nothrow | |
if (s == "-" || s == "+" || s == "*" || s == "/") | |
{ | |
return mixin("(*payload) " ~ s ~ "= rhs"); | |
} | |
} | |
private: | |
T* payload; | |
invariant() | |
{ | |
assert(payload !is null); | |
} | |
} | |
unittest | |
{ | |
int a = 4; | |
auto p = Ref!int(a); | |
assert(p == 4); | |
assert(p > 3); | |
assert(p < 5); | |
p = 10; | |
assert(p == 10); | |
assert(a == 10); | |
p++; | |
assert(p == 11); | |
assert(a == 11); | |
p--; | |
assert(p == 10); | |
assert(a == 10); | |
assert(+p == 10); | |
assert(-p == -10); | |
assert(p + 3 == 13); | |
assert(p - 4 == 6); | |
assert(p*2 == 20); | |
assert(p/2 == 5); | |
p -= 3; | |
assert(p == 7); | |
assert(a == 7); | |
p += 4; | |
assert(p == 11); | |
assert(a == 11); | |
p *= 3; | |
assert(p == 33); | |
assert(a == 33); | |
p /= 11; | |
assert(p == 3); | |
assert(a == 3); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment