implicit construction operator
Meta
jared771 at gmail.com
Mon Feb 26 21:07:52 UTC 2018
On Monday, 26 February 2018 at 19:25:06 UTC, WebFreak001 wrote:
> Now this would be really useful for Variant:
>
> ---
> struct Variant {
> this(U)(U value) @implicit { ... }
> }
>
> void bar(Variant x, Variant y) {}
>
> Variant[] myObjects = [1, 2, "abc", new Node()];
> Variant a = 4;
> bar(4, "asdf");
> ---
This is possible in the language today using the implicit class
construction feature of runtime variadic arrays:
class VArray
{
Variant[] va;
this(T...)(T ts) { foreach(t; ts) { va ~= Variant(t); } }
}
void test(VArray ta...)
{
foreach (v; ta.va)
{
writeln(v.type);
}
}
void main()
{
test(1, "asdf", false);
}
> What's your opinion on this?
This is a very slippery slope to fall down. Even `alias this` is
pushing the limit of what I think we should allow.
That said, there is exactly 1 case where I really, really want
some kind of implicit conversion:
struct Success {}
struct Error { string msg; }
alias Result = Algebraic!(Success, Error);
Result connectToHost(IPAddress host)
{
//do some stuff
if (operationSucceeded)
{
return Success();
}
else
{
return Error(statusMessage);
}
}
This currently doesn't work, and you instead have to return
Result(Success()) and
Result(Error(statusMessage)). I would love to have some way of
implicitly constructing an Algebraic from any of the possible
underlying types. It would bring us very close (if not all the
way) to having Algebraic work identically to sum types in other
languages such as Rust, Swift, Haskell, etc. Having to explicitly
wrapping the values in an Algebraic doesn't seem like a big deal,
but it makes it really annoying to use it in everyday code.
More information about the Digitalmars-d
mailing list