specialization.carbon 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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(T:! type) {
  11. fn Add[self: Self](b: Self) -> Self;
  12. fn Scale[self: Self](v: T) -> Self;
  13. }
  14. class Point(T:! type) {
  15. var x: T;
  16. var y: T;
  17. }
  18. external impl Point(i32) as Vector(i32) {
  19. fn Add[self: Self](b: Self) -> Self {
  20. return {.x = self.x + b.x, .y = self.y + b.y};
  21. }
  22. fn Scale[self: Self](v: i32) -> Self {
  23. return {.x = self.x * v, .y = self.y * v};
  24. }
  25. }
  26. external impl forall [T:! type] Point(T) as Vector(T) {
  27. fn Add[self: Self](b: Self) -> Self {
  28. return self;
  29. }
  30. fn Scale[self: Self](v: T) -> Self {
  31. return self;
  32. }
  33. }
  34. fn AddAndScaleGeneric[T:! Vector(i32)](a: T, b: T, s: i32) -> T {
  35. return a.Add(b).Scale(s);
  36. }
  37. fn Main() -> i32 {
  38. var a: Point(i32) = {.x = 1, .y = 1};
  39. var b: Point(i32) = {.x = 2, .y = 3};
  40. // TODO: This shouldn't be considered ambiguous.
  41. var p: Point(i32) = AddAndScaleGeneric(a, b, 5);
  42. return p.x - 15;
  43. }