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. 4 5 #ifndef BASE_SCOPED_OBSERVATION_TRAITS_H_ 6 #define BASE_SCOPED_OBSERVATION_TRAITS_H_ 7 8 #include "base/scoped_observation_traits_internal.h" 9 10 namespace base { 11 12 // `ScopedObservationTraits` is used to control the behavior of 13 // `ScopedObservation` on sources without AddObserver()/RemoveObserver() 14 // methods. 15 // 16 // The implementation of `ScopedObservation<Source, Observer>` will look up the 17 // most specialized version of `ScopedObservationTraits<Source, Observer>` and 18 // use the corresponding `Traits::AddObserver` and `Traits::RemoveObserver`. 19 // 20 // The default specialization takes care of any Source that exposes 21 // `AddObserver(Observer*)` and `RemoveObserver(Observer*)` methods -- if that's 22 // the case, then `ScopedObservation<Source, Observer>` will work out of the 23 // box. 24 // 25 // However, if your `CustomSource` features custom method names -- say, 26 // `AddFoo(FooObserver*)` and `RemoveFoo(FooObserver*)`, then you'll have to 27 // define a new traits specialization like this: 28 // 29 // `custom_source.h`: 30 // #include "base/scoped_observation_traits.h" 31 // 32 // class FooObserver; 33 // class CustomSource { 34 // public: 35 // void AddFoo(FooObserver*); 36 // void RemoveFoo(FooObserver*); 37 // }; 38 // 39 // namespace base { 40 // 41 // template<> 42 // struct ScopedObservationTraits<CustomSource, FooObserver> { 43 // static void AddObserver(CustomSource* source, 44 // FooObserver* observer) { 45 // source->AddFoo(observer); 46 // } 47 // static void RemoveObserver(CustomSource* source, 48 // FooObserver* observer) { 49 // source->RemoveFoo(observer); 50 // } 51 // }; 52 // 53 // } // namespace base 54 // 55 // `some_important_file.cc`: 56 // // Now this works out of the box. 57 // base::ScopedObservation<CustomSource, FooObserver> obs... 58 // 59 60 template <class Source, class Observer> 61 struct ScopedObservationTraits { 62 static_assert(internal::HasAddAndRemoveObserverMethods<Source, Observer>, 63 "The given Source is missing " 64 "AddObserver(Observer*) and/or RemoveObserver(Observer*) " 65 "methods. Please provide a custom specialization of " 66 "ScopedObservationTraits<> for this Source/Observer pair."); 67 AddObserverScopedObservationTraits68 static void AddObserver(Source* source, Observer* observer) { 69 source->AddObserver(observer); 70 } RemoveObserverScopedObservationTraits71 static void RemoveObserver(Source* source, Observer* observer) { 72 source->RemoveObserver(observer); 73 } 74 }; 75 76 } // namespace base 77 78 #endif // BASE_SCOPED_OBSERVATION_TRAITS_H_ 79