MeshLib
 
Loading...
Searching...
No Matches
TypeCast.h
Go to the documentation of this file.
1#pragma once
2
3#include "Concat.h"
4
5#include <type_traits>
6#include <utility>
7
9template <typename T, typename U>
10inline auto cast_to( U* from )
11{
12 if constexpr ( std::is_const_v<U> )
13 return reinterpret_cast<const T*>( from );
14 else
15 return reinterpret_cast<T*>( from );
16}
17
18template <typename T, typename U>
19inline auto cast_to( U& from )
20{
21 if constexpr ( std::is_const_v<U> )
22 return reinterpret_cast<const T&>( from );
23 else
24 return reinterpret_cast<T&>( from );
25}
26
27template <typename T, typename U>
28inline auto cast_to( U&& from )
29{
30 return reinterpret_cast<T&&>( from );
31}
32
33template <typename T>
34struct auto_cast_trait { };
35
37template <typename U>
38inline auto auto_cast( U&& from )
39{
40 using Base = std::remove_const_t<std::remove_pointer_t<std::remove_reference_t<U>>>;
41 if constexpr ( std::is_arithmetic_v<Base> )
42 {
43 return from;
44 }
45 else
46 {
47 using T = typename auto_cast_trait<Base>::target_type;
48 return cast_to<T>( std::forward<U&&>( from ) );
49 }
50}
51
53#define ADD_AUTO_CAST( From, To ) \
54template <> struct auto_cast_trait<From> { using target_type = To; }
55
57#define REGISTER_AUTO_CAST2( Type1, Type2 ) \
58ADD_AUTO_CAST( Type1, Type2 ); \
59ADD_AUTO_CAST( Type2, Type1 );
60
61#define REGISTER_AUTO_CAST( Type ) \
62REGISTER_AUTO_CAST2( Type, MR_CONCAT( MR, Type ) )
63
72#define ARG( X ) \
73auto&& X = *auto_cast( MR_CONCAT( X, _ ) )
74
76#define ARG_PTR( X ) \
77auto&& X = auto_cast( MR_CONCAT( X, _ ) )
78
80#define ARG_VAL( X ) \
81auto&& X = auto_cast( MR_CONCAT( X, _ ) )
82
84#define ARG_OF( Type, X ) \
85auto&& X = *cast_to<Type>( MR_CONCAT( X, _ ) )
86
88#define ARG_PTR_OF( Type, X ) \
89auto&& X = cast_to<Type>( MR_CONCAT( X, _ ) )
90
92#define ARG_VAL_OF( Type, X ) \
93auto&& X = cast_to<Type>( MR_CONCAT( X, _ ) )
94
96#define RETURN( ... ) \
97return auto_cast( __VA_ARGS__ )
98
100template <typename T, typename U = std::remove_cvref_t<T>>
101inline U* new_from( T&& a )
102{
103 return new U( std::forward<T&&>( a ) );
104}
105
107#define RETURN_NEW( ... ) \
108return auto_cast( new_from( __VA_ARGS__ ) )
109
111#define RETURN_NEW_OF( Type, ... ) \
112return auto_cast( new_from<Type>( __VA_ARGS__ ) )
auto auto_cast(U &&from)
helper function to cast to an associated type
Definition TypeCast.h:38
auto cast_to(U *from)
helper functions to cast types without explicit qualifiers
Definition TypeCast.h:10
U * new_from(T &&a)
helper function to allocate a new object of auto-detected type
Definition TypeCast.h:101
Definition TypeCast.h:34