I have auto function 'f' that might return either an error (with
some text) or a result (with some value). The problem is that the
type of the error is not the same as the type of result so
compilation fails.
Here is my code:
----------
struct Result(T)
{
struct Success
{
static if(!is(T == void))
{
T value;
}
}
struct Failure
{
string error;
}
Algebraic!(Success, Failure) result;
this(Success value)
{
result = value;
}
this(Failure value)
{
result = value;
}
}
auto success(T)(T value)
{
return Result!T(Result!T.Success(value));
}
auto failure(string error)
{
return Result!void(Result!void.Failure(error));
}
auto f(int i)
{
return i > 0 ? success(i) : failure("err text"); // Error:
incompatible types for (success(i)) : (failure("err text")):
Result!int and Result!void
}
-----------------
I can make it work if I add a type to `failure` function but this
remove brevity in usage:
-----------------
auto failure(T)(string error)
{
return Result!T(Result!T.Failure(error));
}
auto f(int i)
{
return i > 0 ? success(i) : failure!int("err text"); //
no error
}
-----------------
How can I make the original code compilable without templatizing
`failure` function?