1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/functional/function_ref.h"
7 #include "testing/gtest/include/gtest/gtest.h"
18 long Method() { return value; }
24 TEST(FunctionRefTest, FreeFunction) {
25 [](FunctionRef<char(float)> ref) { EXPECT_EQ('a', ref(1.0)); }(&Moo);
28 TEST(FunctionRefTest, Method) {
29 [](FunctionRef<long(C*)> ref) {
31 EXPECT_EQ(25L, ref(&c));
35 TEST(FunctionRefTest, Lambda) {
37 auto lambda = [&x]() { return x; };
38 [](FunctionRef<int()> ref) { EXPECT_EQ(3, ref()); }(lambda);
41 // Tests for passing a `base::FunctionRef` as an `absl::FunctionRef`.
42 TEST(FunctionRefTest, AbslConversion) {
43 // Matching signatures should work.
46 auto lambda = [&called](float) {
50 FunctionRef<char(float)> ref(lambda);
51 [](absl::FunctionRef<char(float)> absl_ref) {
57 // `absl::FunctionRef` should be able to adapt "similar enough" signatures.
60 auto lambda = [&called](float) {
64 FunctionRef<char(float)> ref(lambda);
65 [](absl::FunctionRef<void(float)> absl_ref) {
72 // base::FunctionRef allows functors with convertible return types to be
74 TEST(FunctionRefTest, ConvertibleReturnTypes) {
75 // Hopefully this never results in a postmorterm-worthy bug...
77 auto lambda = []() -> bool { return true; };
78 [](FunctionRef<int()> ref) { EXPECT_EQ(1, ref()); }(lambda);
83 class Derived : public Base {};
85 auto lambda = []() -> Derived* { return nullptr; };
86 [](FunctionRef<Base*()> ref) { EXPECT_EQ(nullptr, ref()); }(lambda);