OXYGENHUB
◆ main openmsx / src / utils / checked_cast.hh
722 B · C++ · last changed chore(): initial commit 1 month ago source blame history raw
1
#ifndef CHECKED_CAST_HH
2
#define CHECKED_CAST_HH
3
4
/**
5
 * Based on checked_cast implementation from the book:
6
 *    C++ Coding Standard
7
 *    item 93: Avoid using static_cast on pointers
8
 */
9
10
#include <cassert>
11
#include <type_traits>
12
13
template<typename TO, typename FROM>
14
[[nodiscard]] constexpr TO checked_cast(FROM* from)
15
{
16
	assert(dynamic_cast<TO>(from) == static_cast<TO>(from));
17
	return static_cast<TO>(from);
18
}
19
template<typename TO, typename FROM>
20
[[nodiscard]] constexpr TO checked_cast(FROM& from)
21
{
22
	using TO_PTR = std::remove_reference_t<TO>*;
23
	TO_PTR* suppress_warning = nullptr; (void)suppress_warning;
24
	assert(dynamic_cast<TO_PTR>(&from) == static_cast<TO_PTR>(&from));
25
	return static_cast<TO>(from);
26
}
27
28
#endif