]> git.tdb.fi Git - libs/gl.git/blob - source/bindable.h
Style update: add spaces around assignment operators
[libs/gl.git] / source / bindable.h
1 /* $Id$
2
3 This file is part of libmspgl
4 Copyright © 2010  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #ifndef MSP_GL_BINDABLE_H_
9 #define MSP_GL_BINDABLE_H_
10
11 namespace Msp {
12 namespace GL {
13
14 template<typename T>
15 class Bindable
16 {
17 protected:
18         static const T *cur_obj;
19
20         Bindable() { }
21
22         static bool set_current(const T *obj)
23         {
24                 if(obj==cur_obj)
25                         return false;
26
27                 cur_obj = obj;
28                 return true;
29         }
30
31 public:
32         const T *current() const { return cur_obj; }
33 };
34
35 template<typename T>
36 const T *Bindable<T>::cur_obj;
37
38
39 /**
40 RAII class for binding things.  Binds the thing upon construction and unbinds
41 it upon destruction.  If a null pointer is given, unbinds upon construction and
42 does nothing upon destruction.
43 */
44 class Bind
45 {
46 private:
47         struct Base
48         {
49                 virtual ~Base() { }
50         };
51
52         template<typename T>
53         struct Binder: Base
54         {
55                 const T &obj;
56
57                 Binder(const T &o): obj(o) { obj.bind(); }
58                 ~Binder() { obj.unbind(); }
59         };
60
61         Base *binder;
62
63 public:
64         template<typename T>
65         Bind(const T &o): binder(new Binder<T>(o)) { }
66
67         template<typename T>
68         Bind(const T *o): binder(o ? new Binder<T>(*o) : 0) { if(!o) T::unbind(); }
69
70 private:
71         Bind(const Bind &);
72         Bind &operator=(const Bind &);
73
74 public:
75         ~Bind() { delete binder; }
76 };
77
78 } // namespace GL
79 } // namespace Msp
80
81 #endif