inline double _SQRT_ (double value) { const double half = value * double (0.5) ; union { static_assert (sizeof (double) == sizeof (__int64) ,"") ; double a ; __int64 b ; } tmp ; tmp.a = value ; tmp.b = __int64 (0X5FE6EC85E7DE30DA) - (tmp.b >> 1) ; value = tmp.a ; value *= double (1.5) - value * value * half ; value *= double (1.5) - value * value * half ; value *= double (1.5) - value * value * half ; value = 1 / value ; return value ; }
本人想要一个constexpr型的_SQRT_用于模板当中,例如
在一个参数为SIZE的模板类中本人需要_SQRT_ (SIZE)的额外缓冲区
应该怎么写?
解决方案
50
#include <limits> namespace detail { constexpr double sqrt_newton_raphson(double x, double curr, double prev) { return curr == prev ? curr : sqrt_newton_raphson(x, 0.5 * (curr + x / curr), curr); } } constexpr double cesqrt(double x) { return x >= 0 && x < std::numeric_limits<double>::infinity() ? detail::sqrt_newton_raphson(x, x, 0) : std::numeric_limits<double>::quiet_NaN(); } constexpr size_t ceround(double x) { return size_t(x + 0.5); } template<typename T> auto get_buffer() { constexpr auto st = cesqrt(static_cast<double>(sizeof(T))); constexpr auto len = ceround(st); static char buf[len]; return buf; }
http://stackoverflow.com/questions/8622256/in-c11-is-sqrt-defined-as-constexpr