Skip to content

Instantly share code, notes, and snippets.

@kiljacken
Last active August 29, 2015 14:25
Show Gist options
  • Save kiljacken/8a8963cc176ada88c420 to your computer and use it in GitHub Desktop.
Save kiljacken/8a8963cc176ada88c420 to your computer and use it in GitHub Desktop.
Operation overloading spec draft

Rough sketch follows.

Operator overloading

To prevent the issue, from C++ style operator overloading, of an operator having to be defined on each type involved in th operation, we use based on the syntax for function declarations. This will allow independent definition without any duplication.

operator +(a: Vector2, b: Vector2): Vector2 {
    ...
}

By default operator implementations are considered unordered. Take the case a overload of multiplication between a Vector2 and a f32. The implementation would take the form:

operator *(a: Vector2, b: f32): Vector2 {
    ...
}

By default this will allow both Vector2 * f32 and f32 * Vector2. Not all operations are unordered however. This issue is solved with the introduction of a new attribute [ordered]. To be able to calculate both of the follwing calculations using the [ordered] attribute we would the require two overloads:

[ordered]
operator *(a: Vector2, b: f32): Vector2 { ... }

[ordered]
operator *(a: f32, b: Vector2): Vector2 { ... }

Only the "arithmetic" operators can be overloaded, as to hinder some level of abuse. The semantic of the other operators are very specific and thus would cause confusion if overloaded. The overloadable operations thus are:

  • Addition: a + b
  • Subtraction: a - b
  • Multiplication: a * b
  • Division: a / b
  • Modulo: a % b
@MovingtoMars
Copy link

Comparison operators and bitwise operators should not be overloadable. These are there for comparing or altering raw memory and should not have a special use.

@kiljacken
Copy link
Author

I see the logic in that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment