Sprout/sprout/detail/pow.hpp

57 lines
1.5 KiB
C++
Raw Normal View History

2012-12-06 17:31:16 +00:00
#ifndef SPROUT_DETAIL_POW_HPP
#define SPROUT_DETAIL_POW_HPP
#include <type_traits>
2012-12-06 17:31:16 +00:00
#include <sprout/config.hpp>
#include <sprout/type_traits/is_int.hpp>
#include <sprout/type_traits/is_uint.hpp>
#include <sprout/type_traits/enabler_if.hpp>
2012-12-06 17:31:16 +00:00
namespace sprout {
namespace detail {
template<typename T>
inline SPROUT_CONSTEXPR T
pow2(T const& x) {
return x * x;
}
2012-12-08 04:45:09 +00:00
2012-12-06 17:31:16 +00:00
template<typename T>
inline SPROUT_CONSTEXPR T
pow3(T const& x) {
return x * x * x;
}
2012-12-08 04:45:09 +00:00
template<typename T, typename IntType>
2012-12-06 17:31:16 +00:00
inline SPROUT_CONSTEXPR T
pow_n_impl(T const& x, IntType n) {
2012-12-06 17:31:16 +00:00
return n == 1 ? x
2012-12-08 04:45:09 +00:00
: n % 2 ? x * sprout::detail::pow2(sprout::detail::pow_n_impl(x, n / 2))
: sprout::detail::pow2(sprout::detail::pow_n_impl(x, n / 2))
;
}
template<
typename T, typename UIntType,
typename sprout::enabler_if<sprout::is_uint<UIntType>::value>::type = sprout::enabler
>
2012-12-08 04:45:09 +00:00
inline SPROUT_CONSTEXPR T
pow_n(T const& x, UIntType n) {
2012-12-08 04:45:09 +00:00
return n == 0 ? T(1)
: sprout::detail::pow_n_impl(x, n)
2012-12-06 17:31:16 +00:00
;
}
template<
typename T, typename IntType,
typename sprout::enabler_if<sprout::is_int<IntType>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR T
pow_n(T const& x, IntType n) {
return n == 0 ? T(1)
: n > 0 ? sprout::detail::pow_n_impl(x, n)
: T(1) / sprout::detail::pow_n_impl(x, -n)
;
}
2012-12-06 17:31:16 +00:00
} // namespace detail
} // namespace sprout
#endif // #ifndef SPROUT_DETAIL_POW_HPP