checkandcast.h Source File

API: checkandcast.h Source File
API
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
26namespace omnetpp {
27
28template<class P, class T>
29void 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
60template<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
76template<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
cObject is a lightweight class which serves as the root of the OMNeT++ class hierarchy....
Definition cobject.h:93
Thrown when the simulation kernel or other components detect a runtime error.
Definition cexception.h:343
static cSimulation * getActiveSimulation()
Definition csimulation.h:150
P check_and_cast_nullable(T *p)
A variant of check_and_cast<>() that also allows nullptr as input.
Definition checkandcast.h:77
SIM_API const char * opp_typename(const std::type_info &t)
Returns the name of a C++ type, correcting the quirks of various compilers.
P check_and_cast(T *p)
Cast a pointer to the given pointer type P, and throw exception if fails.
Definition checkandcast.h:61