Template std.typecons.Proxy
Creates a proxy for the value a
that will forward all operations
while disabling implicit conversions. The aliased item a
must be
an lvalue. This is useful for creating a new type from the
"base" type (though this is not a subtype-supertype
relationship; the new type is not related to the old type in any way,
by design).
template Proxy(alias a)
;
The new type supports all operations that the underlying type does,
including all operators such as +
, --
, <
, []
, etc.
Parameters
Name | Description |
---|---|
a | The value to act as a proxy for all operations. It must be an lvalue. |
Example
struct MyInt
{
private int value;
mixin Proxy!value;
this(int n){ value = n; }
}
MyInt n = 10;
// Enable operations that original type has.
++n;
writeln(n); // 11
writeln(n * 2); // 22
void func(int n) { }
// Disable implicit conversions to original type.
//int x = n;
//func(n);
Example
The proxied value must be an lvalue.
struct NewIntType
{
//Won't work; the literal '1'
//is an rvalue, not an lvalue
//mixin Proxy!1;
//Okay, n is an lvalue
int n;
mixin Proxy!n;
this(int n) { this .n = n; }
}
NewIntType nit = 0;
nit++;
writeln(nit); // 1
struct NewObjectType
{
Object obj;
//Ok, obj is an lvalue
mixin Proxy!obj;
this (Object o) { obj = o; }
}
NewObjectType not = new Object();
assert(__traits(compiles, not .toHash()));
Example
There is one exception to the fact that the new type is not related to the old type. Pseudo-member functions are usable with the new type; they will be forwarded on to the proxied value.
import std .math .traits : isInfinity;
float f = 1.0;
assert(!f .isInfinity);
struct NewFloat
{
float _;
mixin Proxy!_;
this(float f) { _ = f; }
}
NewFloat nf = 1.0f;
assert(!nf .isInfinity);
Authors
Andrei Alexandrescu, Bartosz Milewski, Don Clugston, Shin Fujishiro, Kenji Hara