Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / public / renderer / render_frame_observer_tracker.h
blob70b296ffd659fb207d7311a6d739229d7d61047d
1 // Copyright 2013 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.
5 // Helper class used to find the RenderFrameObservers for a given RenderFrame.
6 //
7 // Example usage:
8 //
9 // class MyRFO : public RenderFrameObserver,
10 // public RenderFrameObserverTracker<MyRFO> {
11 // ...
12 // };
14 // MyRFO::MyRFO(RenderFrame* render_frame)
15 // : RenderFrameObserver(render_frame),
16 // RenderFrameObserverTracker<MyRFO>(render_frame) {
17 // ...
18 // }
20 // void SomeFunction(RenderFrame* rf) {
21 // MyRFO* my_rfo = new MyRFO(rf);
22 // MyRFO* my_rfo_tracked = MyRFO::Get(rf);
23 // // my_rfo == my_rfo_tracked
24 // }
26 #ifndef CONTENT_PUBLIC_RENDERER_RENDER_FRAME_OBSERVER_TRACKER_H_
27 #define CONTENT_PUBLIC_RENDERER_RENDER_FRAME_OBSERVER_TRACKER_H_
29 #include <map>
31 #include "base/lazy_instance.h"
33 namespace content {
35 class RenderFrame;
37 template <class T>
38 class RenderFrameObserverTracker {
39 public:
40 static T* Get(const RenderFrame* render_frame) {
41 return static_cast<T*>(render_frame_map_.Get()[render_frame]);
44 explicit RenderFrameObserverTracker(const RenderFrame* render_frame)
45 : render_frame_(render_frame) {
46 render_frame_map_.Get()[render_frame] = this;
48 ~RenderFrameObserverTracker() {
49 render_frame_map_.Get().erase(render_frame_);
52 private:
53 const RenderFrame* render_frame_;
55 static base::LazyInstance<
56 std::map<const RenderFrame*, RenderFrameObserverTracker<T>*>>
57 render_frame_map_;
59 DISALLOW_COPY_AND_ASSIGN(RenderFrameObserverTracker<T>);
62 template <class T>
63 base::LazyInstance<std::map<const RenderFrame*,
64 RenderFrameObserverTracker<T>*>>
65 RenderFrameObserverTracker<T>::render_frame_map_ =
66 LAZY_INSTANCE_INITIALIZER;
68 } // namespace content
70 #endif // CONTENT_PUBLIC_RENDERER_RENDER_FRAME_OBSERVER_TRACKER_H_