IMP  2.0.0
The Integrative Modeling Platform
object_cast.h
Go to the documentation of this file.
1 /**
2  * \file IMP/base/object_cast.h
3  * \brief A shared base class to help in debugging and things.
4  *
5  * Copyright 2007-2013 IMP Inventors. All rights reserved.
6  *
7  */
8 
9 #ifndef IMPBASE_OBJECT_CAST_H
10 #define IMPBASE_OBJECT_CAST_H
11 
12 #include <IMP/base/base_config.h>
13 #include "Object.h"
14 #include "check_macros.h"
15 
16 
17 IMPBASE_BEGIN_NAMESPACE
18 
19 /** Up (or down) cast an \imp Object-derived class. If the cast
20  does not succeed a ValueException will be thrown. Use a
21  \c dynamic_cast if you prefer to have a nullptr returned.
22  */
23 template <class O>
24 inline O* object_cast(Object *o) {
25  O *ret= dynamic_cast<O*>(o);
26  if (!ret) {
27  if (!o) {
28  IMP_THROW("Cannot cast nullptr pointer to desired type.", ValueException);
29  } else {
30  IMP_THROW("Object " << o->get_name() << " cannot be cast to "
31  << "desired type.", ValueException);
32  }
33  }
34  return ret;
35 }
36 
37 
38 IMPBASE_END_NAMESPACE
39 
40 
41 #endif /* IMPBASE_OBJECT_CAST_H */