alpaka
Abstraction Library for Parallel Kernel Acceleration
Loading...
Searching...
No Matches
cast.hpp
Go to the documentation of this file.
1/* Copyright 2025 René Widera
2 * SPDX-License-Identifier: MPL-2.0
3 */
4
5#pragma once
6
8#include "alpaka/trait.hpp"
9
10namespace alpaka
11{
12 namespace internal
13 {
14 struct PCast
15 {
16 template<typename T_To, typename T_Input>
17 struct Op
18 {
19 decltype(auto) operator()(auto&& any) const;
20 };
21 };
22
23 struct LPCast
24 {
25 template<typename T_To, typename T_Input>
26 struct Op
27 {
28 decltype(auto) operator()(auto&& any) const
29 {
30 return PCast::Op<T_To, T_Input>{}(any);
31 }
32 };
33 };
34 } // namespace internal
35
36 /** Performs a static_cast on the storage type of combined data type.
37 *
38 * @code
39 * alpaka::Vec<float, 4> foo{0.f, 0.f, 0.f, 0.f};
40 * alpaka::Vec<int32_t, 4> bar = pCast<int32_t>(foo);
41 * @endcode
42 *
43 * @tparam T_To The target type to which the input is cast.
44 * @param input The input value to be cast. value_type must be castable to `T_To`.
45 * @return input with exchanged value_type
46 */
47 template<typename T_To>
48 constexpr decltype(auto) pCast(auto&& input) requires(isConvertible_v<typename ALPAKA_TYPEOF(input)::type, T_To>)
49 {
50 return internal::PCast::Op<T_To, ALPAKA_TYPEOF(input)>{}(input);
51 }
52
53 /** Performs a static_cast on the storage type of combined data type.
54 *
55 * It ensures that the conversion is lossless by requiring that the value_type of the input is lossless convertible
56 * to the target type `T_To`.
57 *
58 * @code
59 * alpaka::Vec<float, 4> foo{0.f, 0.f, 0.f, 0.f};
60 * // Invalid, loss of precision due to conversion from float to int
61 * // alpaka::Vec<int32_t, 4> bar = lpCast<int32_t>(foo);
62 * alpaka::Vec<double, 4> bar = lpCast<double>(foo);
63 * @endcode
64 *
65 * @tparam T_To The target type to which the input is cast.
66 * @param input The input value to be cast. value_type must be castable to `T_To`.
67 * @return input with exchanged value_type
68 */
69 template<typename T_To>
70 constexpr decltype(auto) lpCast(auto&& input)
71 requires(isLosslesslyConvertible_v<typename ALPAKA_TYPEOF(input)::type, T_To>)
72 {
73 return internal::LPCast::Op<T_To, ALPAKA_TYPEOF(input)>{}(input);
74 }
75} // namespace alpaka
#define ALPAKA_TYPEOF(...)
Get the type of instance.
Definition common.hpp:154
alpaka internal implementations.
Definition generic.hpp:19
main alpaka namespace.
Definition alpaka.hpp:76
constexpr bool isLosslesslyConvertible_v
Definition trait.hpp:122
constexpr bool isConvertible_v
Definition trait.hpp:125
constexpr decltype(auto) lpCast(auto &&input)
Performs a static_cast on the storage type of combined data type.
Definition cast.hpp:70
constexpr decltype(auto) pCast(auto &&input)
Performs a static_cast on the storage type of combined data type.
Definition cast.hpp:48