specialization.carbon 1.1 KB

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