openMSX
Main Page
Namespaces
Classes
Files
File List
File Members
utils
checked_cast.hh
Go to the documentation of this file.
1
#ifndef CHECKED_CAST_HH
2
#define CHECKED_CAST_HH
3
10
#include <cassert>
11
12
/* IMHO this implementation is simpler, but gcc-3.4 and below don't
13
* correctly handle overloading with it (ambiguous overload).
14
*
15
* template<typename T> struct remove_reference
16
* {
17
* typedef T type;
18
* };
19
* template<typename T> struct remove_reference<T&>
20
* {
21
* typedef T type;
22
* };
23
*
24
* template<typename TO, typename FROM>
25
* static TO checked_cast(FROM* from)
26
* {
27
* assert(dynamic_cast<TO>(from) == static_cast<TO>(from));
28
* return static_cast<TO>(from);
29
* }
30
* template<typename TO, typename FROM>
31
* static TO checked_cast(FROM& from)
32
* {
33
* typedef typename remove_reference<TO>::type* TO_PTR;
34
* assert(dynamic_cast<TO_PTR>(&from) == static_cast<TO_PTR>(&from));
35
* return static_cast<TO>(from);
36
* }
37
*
38
* Implementation below can only handle const references, need to find a way
39
* around that.
40
*/
41
template
<
typename
TO,
typename
FROM>
struct
checked_cast_impl
{};
42
template
<
typename
TO,
typename
FROM>
struct
checked_cast_impl
<TO*, FROM>
43
{
44
inline
TO*
operator()
(FROM from) {
45
assert(dynamic_cast<TO*>(from) == static_cast<TO*>(from));
46
return
static_cast<
TO*
>
(from);
47
}
48
};
49
template
<
typename
TO,
typename
FROM>
struct
checked_cast_impl
<TO&, FROM>
50
{
51
inline
TO&
operator()
(
const
FROM& from) {
52
assert(dynamic_cast<TO*>(&from) == static_cast<TO*>(&from));
53
return
static_cast<
TO&
>
(from);
54
}
55
};
56
template
<
typename
TO,
typename
FROM>
57
static
inline
TO checked_cast(
const
FROM& from)
58
{
59
checked_cast_impl<TO, FROM>
caster;
60
return
caster(from);
61
}
62
63
#endif
Generated on Sun May 19 2013 23:16:22 for openMSX by
1.8.1.2