spot 2.11.4.dev
casts.hh
1// -*- coding: utf-8 -*-
2// Copyright (C) 2011, 2015-2018 Laboratoire de Recherche et Développement
3// de l'Epita (LRDE).
4//
5// This file is part of Spot, a model checking library.
6//
7// Spot is free software; you can redistribute it and/or modify it
8// under the terms of the GNU General Public License as published by
9// the Free Software Foundation; either version 3 of the License, or
10// (at your option) any later version.
11//
12// Spot is distributed in the hope that it will be useful, but WITHOUT
13// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15// License for more details.
16//
17// You should have received a copy of the GNU General Public License
18// along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20#pragma once
21
22#include <memory>
23#include <type_traits>
24
25// We usually write code like
26// subtypename* i = down_cast<subtypename*>(m);
27// ... use i ...
28// When NDEBUG is set, the down_cast is a fast static_cast.
29// Otherwise, the down_cast is a dynamic_cast and may return 0
30// on error, which is caught by an assert in the down_cast function.
31//
32// NB: It is valid to use down_cast with non-pointer template argument:
33// subtypename& i = down_cast<subtypename&>(m);
34// If an error occurs during the cast, an exception is thrown.
35//
36// NB: down_cast can also be used on shared_ptr.
37namespace spot
38{
39 template<typename T, typename U>
40 inline
41 T down_cast(U* u) noexcept
42 {
43 SPOT_ASSERT(dynamic_cast<T>(u));
44 return static_cast<T>(u);
45 }
46
47 template<typename T, typename U>
48 inline
49 T down_cast(const std::shared_ptr<U>& u) noexcept
50 {
51 SPOT_ASSERT(std::dynamic_pointer_cast<typename T::element_type>(u));
52 return std::static_pointer_cast<typename T::element_type>(u);
53 }
54
55 template<typename T, typename U>
56 inline
57 T down_cast(U u)
58#ifdef NDEBUG
59 noexcept
60#endif
61 {
62#ifdef NDEBUG
63 return static_cast<T>(u);
64#else
65 return dynamic_cast<T>(u);
66#endif
67 }
68
69} // namespace spot
Definition: automata.hh:27

Please direct any question, comment, or bug report to the Spot mailing list at spot@lrde.epita.fr.
Generated on Fri Feb 27 2015 10:00:07 for spot by doxygen 1.9.4