Implicit conversion of unique objects to mutable and immutable
Ali Çehreli
acehreli at yahoo.com
Tue Jun 21 18:46:51 PDT 2011
On Wed, 22 Jun 2011 00:02:55 +0000, Ali Çehreli wrote:
> I wonder whether a UniqueRef object could be returned, which could allow
> a single casting of its data to mutable or immutable at the call site.
> Further casts could throw, but that would be a runtime solution. :-/
An extremely rough five-minute attempt just to show the idea:
import std.stdio;
import std.exception;
struct UniqueMutable(T)
{
T data;
bool is_used;
this(ref T data)
{
this.is_used = false;
this.data = data;
data = null;
}
T as_mutable()
{
return as_impl!(T)();
}
immutable(T) as_immutable()
{
return as_impl!(immutable(T))();
}
private ConvT as_impl(ConvT)()
{
enforce(!is_used);
ConvT result = cast(ConvT)(data);
data = null;
is_used = true;
return result;
}
}
UniqueMutable!T unique_mutable(T)(ref T data)
{
return UniqueMutable!T(data);
}
/* Now foo() clearly documents that the result is unique and mutable */
UniqueMutable!(char[]) foo()
{
char[] result = "hello".dup;
result ~= " world";
return unique_mutable(result);
}
void main()
{
/* The user can treat it as mutable because it is mutable ... */
char[] mutable_result = foo().as_mutable;
mutable_result[0] = 'H';
/* ... or as immutable from this point on */
string immutable_result = foo().as_immutable;
}
Ali
More information about the Digitalmars-d-learn
mailing list