generic_call_generic.carbon 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. //
  5. // AUTOUPDATE
  6. // RUN: %{explorer-run}
  7. // RUN: %{explorer-run-trace}
  8. // CHECK:STDOUT: result: 0
  9. package ExplorerTest api;
  10. interface Vector {
  11. fn Add[self: Self](b: Self) -> Self;
  12. fn Scale[self: Self](v: i32) -> Self;
  13. }
  14. class Point {
  15. var x: i32;
  16. var y: i32;
  17. impl Point as Vector {
  18. fn Add[self: Point](b: Point) -> Point {
  19. return {.x = self.x + b.x, .y = self.y + b.y};
  20. }
  21. fn Scale[self: Point](v: i32) -> Point {
  22. return {.x = self.x * v, .y = self.y * v};
  23. }
  24. }
  25. }
  26. fn ScaleGeneric[U:! Vector](c: U, s: i32) -> U {
  27. return c.Scale(s);
  28. }
  29. fn AddAndScaleGeneric[T:! Vector](a: T, b: T, s: i32) -> T {
  30. return ScaleGeneric(a.Add(b), s);
  31. }
  32. fn Main() -> i32 {
  33. var a: Point = {.x = 1, .y = 1};
  34. var b: Point = {.x = 2, .y = 3};
  35. var p: Point = AddAndScaleGeneric(a, b, 5);
  36. return p.x - 15;
  37. }