function_ref_unittest.cc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2022 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/functional/function_ref.h"
  5. #include "testing/gtest/include/gtest/gtest.h"
  6. namespace base {
  7. namespace {
  8. char Moo(float) {
  9. return 'a';
  10. }
  11. struct C {
  12. long Method() { return value; }
  13. long value;
  14. };
  15. } // namespace
  16. TEST(FunctionRefTest, FreeFunction) {
  17. [](FunctionRef<char(float)> ref) { EXPECT_EQ('a', ref(1.0)); }(&Moo);
  18. }
  19. TEST(FunctionRefTest, Method) {
  20. [](FunctionRef<long(C*)> ref) {
  21. C c = {.value = 25L};
  22. EXPECT_EQ(25L, ref(&c));
  23. }(&C::Method);
  24. }
  25. TEST(FunctionRefTest, Lambda) {
  26. int x = 3;
  27. auto lambda = [&x]() { return x; };
  28. [](FunctionRef<int()> ref) { EXPECT_EQ(3, ref()); }(lambda);
  29. }
  30. TEST(FunctionRefTest, AbslConversion) {
  31. // Matching signatures should work.
  32. {
  33. bool called = false;
  34. auto lambda = [&called](float) {
  35. called = true;
  36. return 'a';
  37. };
  38. FunctionRef<char(float)> ref(lambda);
  39. [](absl::FunctionRef<char(float)> absl_ref) {
  40. absl_ref(1.0);
  41. }(ref.ToAbsl());
  42. EXPECT_TRUE(called);
  43. }
  44. // `absl::FunctionRef` should be able to adapt "similar enough" signatures.
  45. {
  46. bool called = false;
  47. auto lambda = [&called](float) {
  48. called = true;
  49. return 'a';
  50. };
  51. FunctionRef<char(float)> ref(lambda);
  52. [](absl::FunctionRef<void(float)> absl_ref) {
  53. absl_ref(1.0);
  54. }(ref.ToAbsl());
  55. EXPECT_TRUE(called);
  56. }
  57. }
  58. } // namespace base