ATLAS Offline Software
Loading...
Searching...
No Matches
DVLCast.h
Go to the documentation of this file.
1// This file's extension implies that it's C, but it's really -*- C++ -*-.
2
3/*
4 Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
5*/
6
7// $Id$
14
15
16#ifndef ATHCONTAINERS_TOOLS_DVLCAST_H
17#define ATHCONTAINERS_TOOLS_DVLCAST_H
18
19
20#include <limits>
21#include <limits.h>
22#include <typeinfo>
23#include <cstdlib>
24#include <cstddef>
25
26
27namespace DataModel_detail {
28
29
49template <class DVL, bool has_virtual=DVL::has_virtual> struct DVLCast {};
50
51
55template <class DVL>
56struct DVLCast<DVL, false>
57{
58 typedef typename DVL::base_value_type T;
59
60
65 template <class U>
66 static T* cast (U* b)
67 {
68 return static_cast<T*> (b);
69 }
70
71
76 template <class U>
77 static const T* cast (const U* b)
78 {
79 return static_cast<const T*> (b);
80 }
81};
82
83
87template <class DVL>
88struct DVLCast<DVL, true>
89{
90 typedef typename DVL::base_value_type T;
91
92
96 template <class U>
97 static int find_offset (U* b)
98 {
99 T* ret = dynamic_cast<T*> (b);
100 int offs = reinterpret_cast<char*>(ret) - reinterpret_cast<char*>(b);
101 return offs;
102 }
103
104
109 template <class U>
110 static T* cast (U* b)
111 {
112 // The common case will be for the dynamic type of b to be T.
113 // So test to avoid a dynamic_cast in that case.
114 // The extra test shouldn't add significant overhead
115 // to the case where we really need to run dynamic_cast.
116 if (!b)
117 return 0;
118 if (typeid(*b) == typeid(T)) {
119 static const ptrdiff_t offs = find_offset (b);
120 return reinterpret_cast<T*> (reinterpret_cast<char*>(b) + offs);
121 }
122 else
123 return dynamic_cast<T*> (b);
124 }
125
126
131 template <class U>
132 static const T* cast (const U* b)
133 {
134 // See above.
135 if (!b)
136 return 0;
137 if (typeid(*b) == typeid(T)) {
138 static ptrdiff_t offs = LONG_MAX;
139 if (offs == LONG_MAX) {
140 T* ret = dynamic_cast<const T*> (b);
141 offs = reinterpret_cast<char*>(ret) - reinterpret_cast<char*>(b);
142 return ret;
143 }
144 return reinterpret_cast<const T*> (reinterpret_cast<char*>(b) + offs);
145 }
146 else
147 return dynamic_cast<const T*> (b);
148 }
149};
150
151
152} // namespace DataModel_detail
153
154
155#endif // not ATHCONTAINERS_TOOLS_DVLCAST_H
static T * cast(U *b)
Cast b to a T*.
Definition DVLCast.h:66
static const T * cast(const U *b)
Cast b to a const T*.
Definition DVLCast.h:77
static T * cast(U *b)
Cast b to a T*.
Definition DVLCast.h:110
static const T * cast(const U *b)
Cast b to a const T*.
Definition DVLCast.h:132
static int find_offset(U *b)
Find the offset of T within U.
Definition DVLCast.h:97
casting operations for DataVector/DataList.
Definition DVLCast.h:49