Line data Source code
1 : #ifndef B8E086B0_F27F_43B8_9748_96B243918772
2 : #define B8E086B0_F27F_43B8_9748_96B243918772
3 :
4 : /// \file functions.h
5 : /// \brief Mathematical functions for compile-time computations
6 : ///
7 : /// This file provides mathematical functions that can be evaluated at compile time.
8 : /// The implementation uses modern C++17 constexpr functions for better readability
9 : /// and maintainability compared to template metaprogramming approaches.
10 : ///
11 : /// \note All functions are constexpr and can be used in template parameters
12 : /// and other compile-time contexts.
13 :
14 : #include "base/first_include.h" // IWYU pragma: keep
15 :
16 : namespace tracking
17 : {
18 : namespace math
19 : {
20 : /// \brief Compile-time power function
21 : ///
22 : /// Computes x^N at compile time using a simple iterative approach.
23 : /// This modern C++17 implementation replaces the previous template metaprogramming
24 : /// approach, providing better readability and maintainability while maintaining
25 : /// zero runtime overhead when used with compile-time constants.
26 : ///
27 : /// \tparam N The exponent (must be a compile-time constant, non-negative integer)
28 : /// \tparam T The value type (must support multiplication)
29 : /// \param x The base value
30 : /// \return x raised to the power N
31 : ///
32 : /// \note This function is constexpr and can be used in template parameters
33 : /// \note Negative exponents are not supported (would require floating-point division)
34 : /// \note For runtime exponents, use std::pow from cmath
35 : ///
36 : /// Example usage:
37 : /// \code{.cpp}
38 : /// constexpr double result = tracking::math::pow<3>(2.0); // result = 8.0
39 : /// constexpr int template_param = tracking::math::pow<4>(3); // can be used in templates
40 : /// \endcode
41 : template <int N, class T>
42 1110 : constexpr T pow(T const x)
43 : {
44 : if constexpr (N == 0)
45 : {
46 : return 1; // x^0 = 1 (mathematical convention)
47 : }
48 : else if constexpr (N == 1)
49 : {
50 : return x; // x^1 = x
51 : }
52 : else
53 : {
54 : // Iterative approach for N >= 2
55 1110 : T result = x;
56 2204 : for (int i = 1; i < N; ++i)
57 : {
58 1158 : result *= x;
59 : }
60 : return result;
61 : }
62 : }
63 :
64 : } // namespace math
65 : } // namespace tracking
66 :
67 : #endif // B8E086B0_F27F_43B8_9748_96B243918772
|