Static convertability testing?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 12 13:07:10 PST 2015


On Thursday, February 12, 2015 19:09:45 Chris Williams via Digitalmars-d-learn wrote:
> I have a template function that gets values out of a tree of
> variant types. My goal is to be able to write code like;
>
> node.get!string("path", "to", "leaf");
>
> Inside get(), I would like to use std.conv to dynamically convert
> (where able) to the target type (T) or, if that is not possible,
> to return T.init.
>
> If I wanted to force the user to request the correct type as is
> stored in the structure, I could write code like:
>
> switch (leafType) {
> case STRING:
>     static if (is(T : string)) {
>        return leftValue;
>     }
>     else {
>        return T.init
>     }
> break;
> ...
>
> But since I want to allow all possiblities that std.conv
> supports, I want something like:
>
> static if (isConvertible!(T, string)) {
>     return leftValue.to!T;
> }
> else {
>     return T.init;
> }
>
> Is there something like isConvertible() in the library somewhere?

There are traits in std.traits for testing stuff like
isImplicitlyConvertibel, but std.conv.to is _way_ too fancy to expect any of
the traits in std.traits to tell you whether std.conv.to supports a
particular conversion (and there's every possibility that what std.conv.to
can do will increase from one release to another). By far the simplest way
(and probably the _only_ way realistically) would be to test std.conv.to
itself. Something like

is(typeof({auto t = to!T(string.init);}))

should do the trick for strings, and if you have a variable that you want to
convert from and not just strings, then you could do something like

is(typeof({auto t = to!T(myVar);}))

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list