generic_method_impl.carbon 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. // RUN: %{explorer} %s 2>&1 | \
  6. // RUN: %{FileCheck} --match-full-lines --allow-unused-prefixes=false %s
  7. // RUN: %{explorer} --parser_debug --trace_file=- %s 2>&1 | \
  8. // RUN: %{FileCheck} --match-full-lines --allow-unused-prefixes %s
  9. // AUTOUPDATE: %{explorer} %s
  10. // CHECK: result: 3
  11. package ExplorerTest api;
  12. class Cell(T:! Type) {
  13. fn Create(x: T) -> Cell(T) { return { .data = x }; }
  14. fn Get[me: Self]() -> T {
  15. return me.data;
  16. }
  17. fn Put[addr me: Self*](x: T) {
  18. (*me).data = x;
  19. }
  20. fn Update[addr me: Self*, U:! ImplicitAs(T)](x: U) {
  21. (*me).data = x;
  22. }
  23. fn CreateOther[me: Self, U:! Type](x: U) -> Cell(U) {
  24. return {.data = x};
  25. }
  26. var data: T;
  27. }
  28. class Integer {
  29. var int: i32;
  30. }
  31. fn Main() -> i32 {
  32. var i: Integer = {.int = 1};
  33. var c: Cell(Integer) = Cell(Integer).Create(i); // c contains 1
  34. i = {.int = 2};
  35. var j: Integer = c.Get(); // j == 1
  36. c.Put(i); // c contains 2
  37. c.Update(j); // c contains 1
  38. var d: Cell(Integer) = c.CreateOther(i); // d contains 2
  39. return c.data.int + d.data.int;
  40. }