IMP  2.0.0
The Integrative Modeling Platform
Index.h
Go to the documentation of this file.
1 /**
2  * \file IMP/base/Index.h \brief Basic types used by IMP.
3  *
4  * Copyright 2007-2013 IMP Inventors. All rights reserved.
5  *
6  */
7 
8 #ifndef IMPBASE_INDEX_H
9 #define IMPBASE_INDEX_H
10 
11 #include <IMP/base/base_config.h>
12 #include "bracket_macros.h"
13 #include "showable_macros.h"
14 #include "Value.h"
15 #include <IMP/base/Vector.h>
16 
17 IMPBASE_BEGIN_NAMESPACE
18 /** Define a typed index. This can help disambiguate different
19  integer based indexes floating around to help avoid
20  bugs caused by mixing them up. Care has been taken so
21  that it can be replaced by an integer everywhere, if needed.
22 */
23 template <class Tag>
24 class Index: public Value {
25  int i_;
26  public:
27  explicit Index(int i): i_(i){}
28  Index(): i_(-2){}
29  int get_index() const {
30  IMP_USAGE_CHECK(i_!=-2, "Uninitialized index");
31  IMP_USAGE_CHECK(i_>=0, "Invalid index");
32  return i_;
33  }
36  IMP_USAGE_CHECK(i_!=-2, "Uninitialized index");
37  out << i_;
38  });
40  IMP_USAGE_CHECK(i_!=-2, "Uninitialized index");
41  return i_;
42  });
43 };
44 template <class Tag>
45 inline unsigned int get_as_unsigned_int(Index<Tag> i) {
46  return i.get_index();
47 }
48 template <class Tag>
49 inline Index<Tag> get_invalid_index() {
50  return Index<Tag>(-1);
51 }
52 
53 /** This class implements a vector tied to a particular index.
54  */
55 template <class Tag, class T>
56 class IndexVector: public Vector<T> {
57  typedef Vector<T> P;
58  public:
59  IndexVector(unsigned int sz, const T&t=T()):
60  P(sz, t){}
61  IndexVector(){}
62  IMP_BRACKET(T, Index<Tag>, get_as_unsigned_int(i) < P::size(),
63  return P::operator[](get_as_unsigned_int(i)));
64 };
65 
66 template <class Tag, class Container, class T>
67 void resize_to_fit(Container &v, Index<Tag> i,
68  const T&default_value=T()) {
69  if (v.size() <=get_as_unsigned_int(i)) {
70  v.resize(get_as_unsigned_int(i)+1, default_value);
71  }
72 }
73 
74 IMPBASE_END_NAMESPACE
75 
76 #endif /* IMPBASE_INDEX_H */