tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
abs.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2019 Tobias Hienzsch
3
4#ifndef TETL_MATH_ABS_HPP
5#define TETL_MATH_ABS_HPP
6
7#include <etl/_config/all.hpp>
8
9#include <etl/_concepts/same_as.hpp>
10#include <etl/_type_traits/is_constant_evaluated.hpp>
11
12namespace etl {
13namespace detail {
14
15inline constexpr struct abs {
16 template <typename T>
17 [[nodiscard]] constexpr auto operator()(T arg) const noexcept -> T
18 {
19 if (arg >= T(0)) {
20 return arg;
21 }
22 return arg * T(-1);
23 }
24} abs;
25
26inline constexpr struct fabs {
27 template <typename Float>
28 [[nodiscard]] constexpr auto operator()(Float arg) const noexcept -> Float
29 {
31#if __has_builtin(__builtin_fabsf)
32 if constexpr (etl::same_as<Float, float>) {
33 return __builtin_fabsf(arg);
34 }
35#endif
36#if __has_builtin(__builtin_fabs)
37 if constexpr (etl::same_as<Float, double>) {
38 return __builtin_fabs(arg);
39 }
40#endif
41 }
42 return etl::detail::abs(arg);
43 }
44} fabs;
45
46} // namespace detail
47
48/// \brief Computes the absolute value of an integer number. The behavior is
49/// undefined if the result cannot be represented by the return type. If abs
50/// is called with an unsigned integral argument that cannot be converted to int
51/// by integral promotion, the program is ill-formed.
52[[nodiscard]] constexpr auto abs(int arg) noexcept -> int
53{
54 return etl::detail::abs(arg);
55}
56
57[[nodiscard]] constexpr auto abs(long arg) noexcept -> long
58{
59 return etl::detail::abs(arg);
60}
61
62[[nodiscard]] constexpr auto abs(long long arg) noexcept -> long long
63{
64 return etl::detail::abs(arg);
65}
66
67[[nodiscard]] constexpr auto abs(float arg) noexcept -> float
68{
69 return etl::detail::abs(arg);
70}
71
72[[nodiscard]] constexpr auto abs(double arg) noexcept -> double
73{
74 return etl::detail::abs(arg);
75}
76
77[[nodiscard]] constexpr auto abs(long double arg) noexcept -> long double
78{
79 return etl::detail::abs(arg);
80}
81
82} // namespace etl
83
84#endif // TETL_MATH_ABS_HPP
Definition adjacent_find.hpp:9
constexpr auto abs(float arg) noexcept -> float
Definition abs.hpp:67
constexpr auto abs(long double arg) noexcept -> long double
Definition abs.hpp:77
constexpr auto is_constant_evaluated() noexcept -> bool
Detects whether the function call occurs within a constant-evaluated context. Returns true if the eva...
Definition is_constant_evaluated.hpp:17
constexpr auto abs(long arg) noexcept -> long
Definition abs.hpp:57
constexpr auto abs(double arg) noexcept -> double
Definition abs.hpp:72
constexpr auto abs(long long arg) noexcept -> long long
Definition abs.hpp:62
constexpr auto abs(int arg) noexcept -> int
Computes the absolute value of an integer number. The behavior is undefined if the result cannot be r...
Definition abs.hpp:52