YACLib
C++ library for concurrent tasks execution
Loading...
Searching...
No Matches
cast.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <memory>
4#include <type_traits>
5
6namespace yaclib {
7
8template <typename To, typename From>
9constexpr auto* UpCast(From* from) noexcept {
10 using RawTo = std::remove_const_t<To>;
11 using RawFrom = std::remove_const_t<From>;
12 static_assert(!std::is_pointer_v<RawTo>, "'To' shouldn't be pointer");
13 static_assert(!std::is_reference_v<RawTo>, "'To' shouldn't be reference");
14 using CastTo = std::conditional_t<std::is_const_v<From>, const RawTo, To>;
15 static_assert(!std::is_same_v<RawTo, RawFrom>);
16 static_assert(std::is_base_of_v<RawTo, RawFrom>);
17 return static_cast<CastTo*>(from);
18}
19
20template <typename To, typename From, typename = std::enable_if_t<!std::is_pointer_v<From>>>
21constexpr auto& UpCast(From& from) noexcept {
22 return *UpCast<To>(std::addressof(from));
23}
24
25template <typename To, typename From>
26constexpr auto* DownCast(From* from) noexcept {
27 using RawTo = std::remove_const_t<To>;
28 using RawFrom = std::remove_const_t<From>;
29 static_assert(!std::is_pointer_v<RawTo>, "'To' shouldn't be pointer");
30 static_assert(!std::is_reference_v<RawTo>, "'To' shouldn't be reference");
31 using CastTo = std::conditional_t<std::is_const_v<From>, const RawTo, To>;
32 static_assert(!std::is_same_v<RawFrom, RawTo>);
33 static_assert(std::is_base_of_v<RawFrom, RawTo>);
34 YACLIB_ASSERT(from == nullptr || dynamic_cast<CastTo*>(from) != nullptr);
35 return static_cast<CastTo*>(from);
36}
37
38template <typename To, typename From>
39constexpr auto& DownCast(From& from) noexcept {
40 return *DownCast<To>(std::addressof(from));
41}
42
43} // namespace yaclib
#define YACLIB_ASSERT(cond)
Definition log.hpp:85
constexpr auto * DownCast(From *from) noexcept
Definition cast.hpp:26
Contract< V, E > MakeContract()
Creates related future and promise.
Definition contract.hpp:25
constexpr auto * UpCast(From *from) noexcept
Definition cast.hpp:9