Skip to content

Instantly share code, notes, and snippets.

@pszturmaj
Created October 19, 2011 17:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pszturmaj/1299046 to your computer and use it in GitHub Desktop.
Save pszturmaj/1299046 to your computer and use it in GitHub Desktop.
Conversion between composite types
/**
Object-to-object conversion converts each field in turn. Possible conversions are
between tuples, structs and classes. Target class must have a default constructor.
*/
T toImpl(T, S)(S src)
if (!isImplicitlyConvertible!(S, T) &&
!is(typeof(T(src))) && !is(typeof(new T(src))) && // don't conflict with converting construction
!isAssociativeArray!T && !isAssociativeArray!S && // don't conflict with AA conversion
!is(typeof(S.init.opCast!T()) : T) && // don't conflict with opCast conversion
!is(T == union) && !is(S == union) && // unions not supported
is(typeof(T.tupleof)) && is(typeof(S.tupleof)))
{
static if (is(T == class))
T result = new T();
else
T result;
foreach (i, v; src.tupleof)
result.tupleof[i] = to!(typeof(result.tupleof[i]))(v);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment