Trax3 3.1.0
trax track library
Loading...
Searching...
No Matches
NarrowCast.h
1// trax track library
2// AD 2022
3//
4// "the resolution of all the fruitless searches"
5//
6// Peter Gabriel
7//
8//
9// Copyright (c) 2025 Trend Redaktions- und Verlagsgesellschaft mbH
10// Copyright (c) 2019 Marc-Michael Horstmann
11//
12// Permission is hereby granted to any person obtaining a copy of this software
13// and associated source code (the "Software"), to use, view, and study the
14// Software for personal or internal business purposes, subject to the following
15// conditions:
16//
17// 1. Redistribution, modification, sublicensing, or commercial use of the
18// Software is NOT permitted without prior written consent from the copyright
19// holder.
20//
21// 2. The Software is provided "AS IS", without warranty of any kind, express
22// or implied.
23//
24// 3. All copies of the Software must retain this license notice.
25//
26// For further information, please contact: horstmann.marc@trendverlag.de
27
28#pragma once
29
30#include <memory>
31#include <stdexcept>
32
33namespace common{
34
36 template<typename Target, typename Source>
37 struct NarrowCast_Imp {
38 static inline Target narrow_cast( Source v ) {
39 const Target r = static_cast<Target>(v);
40 if( static_cast<Source>(r) != v )
41 throw std::runtime_error("narrow_cast<>() failed");
42
43 return r;
44 }
45 };
46
47 template<typename SameType>
48 struct NarrowCast_Imp<SameType, SameType> {
49 static inline SameType narrow_cast( SameType v ) noexcept {
50 return v;
51 }
52 };
54
59 template<typename Target, typename Source>
60 inline Target narrow_cast( Source v ){
61 return NarrowCast_Imp<Target, Source>::narrow_cast(v);
62 }
63
64
65 template <typename Target, typename Source>
66 std::unique_ptr<Target> dynamic_unique_cast(std::unique_ptr<Source>&& source) {
67 if( auto* casted = dynamic_cast<Target*>(source.get()) ) {
68 source.release();
69 return std::unique_ptr<Target>( casted );
70 }
71
72 return nullptr;
73 }
74
75}
Namespace of common utility classes and methods.
Definition Helpers.h:43
Target narrow_cast(Source v)
Safe cast for casting numeric values.
Definition NarrowCast.h:60