IMP logo
IMP Reference Guide  develop.63b38c487d,2024/12/21
The Integrative Modeling Platform
object_cast.h
Go to the documentation of this file.
1 /**
2  * \file IMP/object_cast.h
3  * \brief Up (or down) cast an \imp Object-derived class.
4  *
5  * Copyright 2007-2022 IMP Inventors. All rights reserved.
6  *
7  */
8 
9 #ifndef IMPKERNEL_OBJECT_CAST_H
10 #define IMPKERNEL_OBJECT_CAST_H
11 
12 #include <IMP/kernel_config.h>
13 #include "Object.h"
14 #include "check_macros.h"
15 
16 IMPKERNEL_BEGIN_NAMESPACE
17 
18 //! Up (or down) cast an \imp Object-derived class.
19 /** If the cast does not succeed a ValueException will be thrown.
20  Use a \c dynamic_cast if you prefer to have a nullptr returned.
21  */
22 template <class O>
23 inline O *object_cast(Object *o) {
24  O *ret = dynamic_cast<O *>(o);
25  if (!ret) {
26  if (!o) {
27  IMP_THROW("Cannot cast nullptr pointer to desired type.", ValueException);
28  } else {
29  IMP_THROW("Object " << o->get_name() << " cannot be cast to "
30  << "desired type.",
32  }
33  }
34  return ret;
35 }
36 
37 IMPKERNEL_END_NAMESPACE
38 
39 #endif /* IMPKERNEL_OBJECT_CAST_H */
Common base class for heavy weight IMP objects.
Definition: Object.h:111
O * object_cast(Object *o)
Up (or down) cast an IMP Object-derived class.
Definition: object_cast.h:23
#define IMP_THROW(message, exception_name)
Throw an exception with a message.
Definition: check_macros.h:50
Helper macros for throwing and handling exceptions.
A shared base class to help in debugging and things.
An exception for an invalid value being passed to IMP.
Definition: exception.h:136