specialization.carbon 1.1 KB

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