www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Better casts?

reply "Mehrdad" <wfunction hotmail.com> writes:
I've made a bunch of new casts and templates that IMHO should be 
added to traits.d.

What do people think?


ref auto Mutable!(T) mutable(T)(ref auto T v) { return 
cast(typeof(return))v; }
unittest
{
	int x = 5;
	static assert(is(typeof(mutable(x)) == typeof(x)));
	static assert(is(typeof(mutable(cast(immutable)x)) == 
typeof(x)));
	static assert(is(typeof(mutable(cast(shared)x)) == 
shared(typeof(x))));
	static assert(is(typeof(mutable(x) = x) == typeof(x)));
}

ref auto Unconst!(T) unconst(T)(ref auto T v) { return 
cast(typeof(return))v; }
unittest
{
	int x = 5;
	static assert(is(typeof(unconst(x)) == typeof(x)));
	static assert(is(typeof(unconst(cast(const)x)) == typeof(x)));
	static assert(is(typeof(unconst(cast(immutable)x)) == 
immutable(typeof(x))));
	static assert(is(typeof(unconst(x) = x) == typeof(x)));
}

ref auto Unshared!(T) unshared(T)(ref auto T v) { return 
cast(typeof(return))v; }
unittest
{
	int x = 5;
	static assert(is(typeof(unshared(x)) == typeof(x)));
	static assert(is(typeof(unshared(cast(shared)x)) == typeof(x)));
	static assert(is(typeof(unshared(cast(immutable)x)) == 
immutable(typeof(x))));
	static assert(is(typeof(unshared(x) = x) == typeof(x)));
}

template Unconst(T)
{
	static if (is(T U == const U)) { alias U Unconst; }
	else { alias T Unconst; }
}
unittest
{
	static assert(is(Unconst!(const(int*)) == const(int)*));
}

template Unshared(T)
{
	static if (is(T U == shared U)) { alias U Unshared; }
	else { alias T Unshared; }
}
unittest
{
	static assert(is(Unshared!(shared(int*)) == shared(int)*));
}

template Mutable(T)
{
	static if (is(T U == immutable U)) { alias U Mutable; }
	else { alias T Mutable; }
}
unittest
{
	static assert(is(Mutable!(immutable(int*)) == immutable(int)*));
	static assert(is(Mutable!(const(shared(int))) == 
const(shared(int))));
}

template WithQual(T, F)
{
	static if (is(F U == const U) && !is(T == const T)) { alias 
WithQual!(const T, F) WithQual; }
	else static if (is(F U == shared U) && !is(T == shared T)) { 
alias WithQual!(shared T, F) WithQual; }
	else static if (is(F U == immutable U) && !is(T == immutable T)) 
{ alias WithQual!(immutable T, F) WithQual; }
	else { alias T WithQual; }
}
unittest
{
	static assert(is(WithQual!(int, const int) == const int));
	static assert(is(WithQual!(int, shared int) == shared int));
	static assert(is(WithQual!(int, immutable int) == immutable 
int));
}
Jun 06 2012
parent "bearophile" <bearophileHUGS lycos.com> writes:
Mehrdad:

 What do people think?

I think some specialized and safe casts will be good to have in Phobos: http://d.puremagic.com/issues/show_bug.cgi?id=5559 Bye, bearophile
Jun 07 2012