OMNeT++ Simulation Library  6.0.3
checkandcast.h
1 //==========================================================================
2 // CHECKANDCAST.H - part of
3 // OMNeT++/OMNEST
4 // Discrete System Simulation in C++
5 //
6 //==========================================================================
7 
8 /*--------------------------------------------------------------*
9  Copyright (C) 1992-2017 Andras Varga
10  Copyright (C) 2006-2017 OpenSim Ltd.
11 
12  This file is distributed WITHOUT ANY WARRANTY. See the file
13  `license' for details on this and other legal matters.
14 *--------------------------------------------------------------*/
15 
16 #ifndef __OMNETPP_CHECKANDCAST_H
17 #define __OMNETPP_CHECKANDCAST_H
18 
19 #include <typeinfo>
20 #include "simkerneldefs.h"
21 #include "cownedobject.h"
22 #include "cexception.h"
23 #include "cmodule.h"
24 #include "csimulation.h"
25 
26 namespace omnetpp {
27 
28 template<class P, class T>
29 void check_and_cast_failure(T *p, P ret)
30 {
31  const cObject *o = dynamic_cast<const cObject *>(p);
32  if (o)
33  throw cRuntimeError("check_and_cast(): Cannot cast (%s*)%s to type '%s'",
34  o->getClassName(),
35  o->getOwner() == cSimulation::getActiveSimulation()->getContextModule() ? o->getFullName() : o->getFullPath().c_str(),
36  opp_typename(typeid(P)));
37  else
38  throw cRuntimeError("check_and_cast(): Cannot cast '%s*' to type '%s'",
39  opp_typename(typeid(T)),
40  opp_typename(typeid(P)));
41 }
42 
60 template<class P, class T>
62 {
63  if (!p)
64  throw cRuntimeError("check_and_cast(): Cannot cast nullptr to type '%s'", opp_typename(typeid(P)));
65  P ret = dynamic_cast<P>(p);
66  if (!ret)
67  check_and_cast_failure(p, ret);
68  return ret;
69 }
70 
76 template<class P, class T>
78 {
79  if (!p)
80  return nullptr;
81  P ret = dynamic_cast<P>(p);
82  if (!ret)
83  check_and_cast_failure(p, ret);
84  return ret;
85 }
86 
87 } // namespace omnetpp
88 
89 #endif
90 
omnetpp::cSimulation::getContextModule
cModule * getContextModule() const
omnetpp::cModule::getFullName
virtual const char * getFullName() const override
omnetpp::check_and_cast_nullable
P check_and_cast_nullable(T *p)
A variant of check_and_cast<>() that also allows nullptr as input.
Definition: checkandcast.h:77
omnetpp::check_and_cast
P check_and_cast(T *p)
Cast a pointer to the given pointer type P, and throw exception if fails.
Definition: checkandcast.h:61
omnetpp::cRuntimeError
Thrown when the simulation kernel or other components detect a runtime error.
Definition: cexception.h:286
omnetpp::cSimulation::getActiveSimulation
static cSimulation * getActiveSimulation()
Definition: csimulation.h:143
omnetpp::opp_typename
const SIM_API char * opp_typename(const std::type_info &t)
Returns the name of a C++ type, correcting the quirks of various compilers.