[gdb/testsuite] Allow nodebug srcfile in gdb.base/unwind-on-each-insn.exp
[binutils-gdb.git] / gdbsupport / gdb-checked-static-cast.h
blobcc298733fadb61dd20755298c2b41fc9dc2a535b
1 /* Copyright (C) 2022-2023 Free Software Foundation, Inc.
3 This file is part of GDB.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 #ifndef COMMON_GDB_CHECKED_DYNAMIC_CAST_H
19 #define COMMON_GDB_CHECKED_DYNAMIC_CAST_H
21 #include "gdbsupport/traits.h"
23 namespace gdb
26 /* This function can be used in place of static_cast when casting between
27 pointers of polymorphic types. The benefit of using this call is that,
28 when compiling in developer mode, dynamic_cast will be used to validate
29 the cast. This use of dynamic_cast is why this function will only
30 work for polymorphic types.
32 In non-developer (i.e. production) builds, the dynamic_cast is replaced
33 with a static_cast which is usually significantly faster. */
35 template<typename T, typename V>
37 checked_static_cast (V *v)
39 /* We only support casting to pointer types. */
40 static_assert (std::is_pointer<T>::value, "target must be a pointer type");
42 /* Check for polymorphic types explicitly in case we're in release mode. */
43 static_assert (std::is_polymorphic<V>::value, "types must be polymorphic");
45 /* Figure out the type that T points to. */
46 using T_no_P = typename std::remove_pointer<T>::type;
48 /* In developer mode this cast uses dynamic_cast to confirm at run-time
49 that the cast from V* to T is valid. However, we can catch some
50 mistakes at compile time, this assert prevents anything other than
51 downcasts, or casts to same type. */
52 static_assert (std::is_base_of<V, T_no_P>::value
53 || std::is_base_of<T_no_P, V>::value,
54 "types must be related");
56 #ifdef DEVELOPMENT
57 T result = dynamic_cast<T> (v);
58 gdb_assert (result != nullptr);
59 #else
60 T result = static_cast<T> (v);
61 #endif
63 return result;
68 #endif /* COMMON_GDB_CHECKED_DYNAMIC_CAST_H */