openMSX
checked_cast.hh
Go to the documentation of this file.
1#ifndef CHECKED_CAST_HH
2#define CHECKED_CAST_HH
3
10#include <type_traits>
11#include <cassert>
12
13template<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}
19template<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
constexpr TO checked_cast(FROM *from)
Based on checked_cast implementation from the book: C++ Coding Standard item 93: Avoid using static_c...