www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Implicit conversion without alias this?

reply maik klein <maikklein googlemail.com> writes:
I have my own version of Algebraic

struct Ok(T){
     T value;
}

struct Err(E){
     E value;
}

auto ok(T)(auto ref T value){
     return Ok!T(value);
}

auto err(E)(auto ref E err){
     return Err!E(err);
}

alias Result(T, E) = Algebraic!(Ok!T, Err!E);

I have a constructor and opAssign which allows me to write

Result!(int, string) res = ok(5);

But it seems strange that I can not do the same thing to function 
returns

Result!(int, string) test(){
     return ok(5); // Error: cannot implicitly convert expression 
(ok(5)) of type Ok!int to Algebraic!(Ok!int, Err!string)
}

I can not add implicit conversion with alias this from Ok!T to 
Result!(T, ???) because "Ok" doesn't know about the error type.

That is a bit unergonomic because I always seem to need the full 
type

like

auto ok(T, E)(auto ref T value){
     return Result!(T, E)(Ok!T(value));
}

I basically try to mirror 
http://rustbyexample.com/std/result.html but I don't think that 
is possible.

Any ideas?
Jun 03 2016
parent Jonathan M Davis via Digitalmars-d-learn writes:
On Friday, June 03, 2016 16:12:50 maik klein via Digitalmars-d-learn wrote:
 Any ideas?
Well, alias this is the only way that D supports any kind of implicit conversions for user-defined types. So, if you want to have an implicit conversion for your type, you're going to have to figure out how to do it with alias this. If you can't, then you can't have an implicit version. - Jonathan M Davis
Jun 03 2016