db39bfb631f315f45290b3a410b9bba6cabf4c9b
[libdcp.git] / src / ref.h
1 /*
2     Copyright (C) 2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifndef LIBDCP_REF_H
21 #define LIBDCP_REF_H
22
23 #include "exceptions.h"
24 #include "object.h"
25 #include <boost/shared_ptr.hpp>
26 #include <string>
27
28 namespace dcp {
29
30 template<class T>
31 class Ref
32 {
33 public:
34         Ref (std::string id)
35                 : _id (id)
36         {}
37
38         Ref (boost::shared_ptr<T> object)
39                 : _id (object->id ())
40                 , _object (object)
41         {}
42
43         void set_id (std::string id)
44         {
45                 _id = id;
46         }
47
48         void resolve (std::list<boost::shared_ptr<Object> > objects)
49         {
50                 typename std::list<boost::shared_ptr<Object> >::iterator i = objects.begin();
51                 while (i != objects.end() && (*i)->id() != _id) {
52                         ++i;
53                 }
54
55                 if (i != objects.end ()) {
56                         _object = boost::dynamic_pointer_cast<T> (*i);
57                 }
58         }
59
60         std::string id () const {
61                 return _id;
62         }
63
64         boost::shared_ptr<T> object () const {
65                 if (!_object) {
66                         throw UnresolvedRefError (_id);
67                 }
68
69                 return _object;
70         }
71
72         T * operator->() const {
73                 if (!_object) {
74                         throw UnresolvedRefError (_id);
75                 }
76
77                 return _object.get ();
78         }
79
80         bool resolved () const {
81                 return _object;
82         }
83
84 private:
85         std::string _id;
86         boost::shared_ptr<T> _object;
87 };
88
89 }
90
91 #endif