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

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