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 #ifndef BASE_SCOPED_OBSERVATION_TRAITS_H_
6 #define BASE_SCOPED_OBSERVATION_TRAITS_H_
8 #include "base/scoped_observation_traits_internal.h"
12 // `ScopedObservationTraits` is used to control the behavior of
13 // `ScopedObservation` on sources without AddObserver()/RemoveObserver()
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`.
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
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:
30 // #include "base/scoped_observation_traits.h"
33 // class CustomSource {
35 // void AddFoo(FooObserver*);
36 // void RemoveFoo(FooObserver*);
42 // struct ScopedObservationTraits<CustomSource, FooObserver> {
43 // static void AddObserver(CustomSource* source,
44 // FooObserver* observer) {
45 // source->AddFoo(observer);
47 // static void RemoveObserver(CustomSource* source,
48 // FooObserver* observer) {
49 // source->RemoveFoo(observer);
53 // } // namespace base
55 // `some_important_file.cc`:
56 // // Now this works out of the box.
57 // base::ScopedObservation<CustomSource, FooObserver> obs...
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.");
68 static void AddObserver(Source* source, Observer* observer) {
69 source->AddObserver(observer);
71 static void RemoveObserver(Source* source, Observer* observer) {
72 source->RemoveObserver(observer);
78 #endif // BASE_SCOPED_OBSERVATION_TRAITS_H_