std::chrono::abs(std::chrono::duration)

From cppreference.com
< cpp‎ | chrono‎ | duration
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
 
 
Defined in header <chrono>
template <class Rep, class Period>
constexpr std::chrono::duration<Rep, Period> abs( std::chrono::duration<Rep, Period> d );
(since C++17)

Returns the absolute value of the duration d. Specifically, if d >= d.zero(), return d, otherwise return -d.

The function does not participate in the overload resolution unless std::numeric_limits<Rep>::is_signed is true.

Parameters

d - duration

Return value

Absolute value of d

Possible implementation

template <class Rep, class Period, class = std::enable_if_t<
   std::chrono::duration<Rep, Period>::min() < std::chrono::duration<Rep, Period>::zero()>>
constexpr std::chrono::duration<Rep, Period> abs(std::chrono::duration<Rep, Period> d)
{
    return d >= d.zero() ? d : -d;
}

Example

#include <iostream>
#include <chrono>
 
int main()
{
    using namespace std::chrono;
 
    static_assert(abs(-42s) == std::chrono::abs(42s));
 
    std::cout << "abs(+3min) = " << abs(3min).count() << '\n'
              << "abs(-3min) = " << abs(-3min).count() << '\n';
}

Output:

abs(+3min) = 3
abs(-3min) = 3

See also

implements unary + and unary -
(public member function)
computes absolute value of an integral value (|x|)
(function)