Getting resulting/return type from operation in templates

Rekel paultjeadriaanse at gmail.com
Tue Jul 6 14:43:26 UTC 2021


On Tuesday, 6 July 2021 at 14:27:35 UTC, Paul Backus wrote:
> Instead of having the template evaluate to a `bool`, have it 
> evaluate to the type of the result:
>
> ```d
> alias ResultType(Lhs, string op, Rhs) =
>     typeof(((Lhs lhs, Rhs rhs) => mixin("lhs", op, "rhs"))());
>
> static assert(is(ResultType!(int, "+", double) == double));
> static assert(is(ResultType!(string, "~", string) == string));
> static assert(!is(ResultType!(string, "+", int))); // no valid 
> result type
> ```
>
> Then you can use `is()` in the template constraints to check 
> whether the operation is supported:
>
> ```d
> auto opBinary(string op, Rhs: T2[], T2) const
>     if (is(ResultType!(T, op, T2)))
> {
>     Vec!(ResultType!(T, op, T2), L) result;
>     // etc.
> }
> ```

Oh that's neat, thanks.
I guess that would make it:
```d
auto opBinary(string op, R)(R right) const if (is(ResultType!(T, 
op, R))) {
	Vec!(ResultType!(T, op, R), L) result;
	static foreach (i; 0 .. L) {
		mixin("result[i] = this[i] " ~ op ~ " right;");
	}
	return result;
}
```

I guess I'll just have to take the result definition for what it 
is. At least the return type can use auto, haha. Imagine using 
ResultType!(T, op, R) thrice...

Is there any reason the function call in the alias is acceptable? 
I would imagine the () part would actually require 2 parameters.



More information about the Digitalmars-d-learn mailing list