For the operator +
to be defined on any two Value<T>
and Value<U>
, where T
and U
are any types, the operator needs to be generic. Using some made-up syntax, it would look something like:
class Value<T> {
public static Result<T,U> operator+<U>(Value<T> a, Value<U> b) {
// create a Result<T, U>
}
}
However, the syntax of user-defined operators is very strict, and is nowhere like that of method declarations:
operator_declaration
: attributes? operator_modifier+ operator_declarator operator_body
;
operator_declarator
: unary_operator_declarator
| binary_operator_declarator
| conversion_operator_declarator
;
binary_operator_declarator
: type 'operator' overloadable_binary_operator '(' type identifier ',' type identifier ')'
;
overloadable_binary_operator
: '+' | '-' | '*' | '/' | '%' | '&' | '|' | '^' | '<<'
| right_shift | '==' | '!=' | '>' | '<' | '>=' | '<='
;
operator_body
: block
| '=>' expression ';'
| ';'
;
Though they may look a lot like method declarations, their syntax is specified in a very different way, and do not allow generic parameters.
Furthermore, using this hypothetical generic operator would require type inference, which is applied when invoking a method. This does not happen during operator resolution.
As a workaround, you can declare a Plus
method:
class Value<T> {
public Result<T,U> Plus<U>(Value<U> other) {
// create a Result<T, U>
}
}
// You'd be doing a.Plus(b), rather than "a + b"
// You still get the type inference you wanted
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…