我使用 constexpr
关键字来计算在编译时能够存储在 float 或 double 中的最大整数值(n 是尾数中的位数,val 初始值为 1.0):
constexpr double calc_max_float(int n, double val)
{
return (n == 0) ? (val) : calc_max_float(n - 1, 2.0*val);
}
生成此值供以下模板使用:
template <bool, class L, class R>
struct IF // primary template
{
typedef R type;
};
template <class L, class R>
struct IF<true, L, R> // partial specialization
{
typedef L type;
};
template<class float_type>
inline float_type extract_float()
{
return (extract_integer<typename IF<sizeof(float_type) == 4,
uint32_t,
uint64_t
>::type
>() >> (8*sizeof(float_type) - std::numeric_limits<float_type>::digits))*(1./calc_max_float(std::numeric_limits<float_type>::digits, 1.0));
}
这个模板生成两个函数,相当于:
inline float extract_single()
{
return (extract_integer<uint32_t>() >> 9) * (1./(8388608.0));
}
inline double extract_double()
{
return (extract_integer<uint64_t>() >> 12) * (1./(67108864.0*67108864.0));
}
在 GCC 中一切都很好,但是我希望也能够使用 VC11/12 进行编译。关于如何替换 constexpr calc_max_float(int n, double val)
有什么想法吗?
编辑:
明确地说,我正在寻找一种在编译时使用模板计算常量 pow(2,x) 的方法。即使是朝着正确的方向前进也会很棒。
至于用法示例,我有一个函数 extract_integer(type min, type range),它适用于任何有符号或无符号类型。我正在尝试创建一个函数 extract_float(),它返回一个 float 或 double 类型的值 [0,1)。
我想我正在寻找类似的东西:
template <const unsigned N, const uint64_t val>
inline uint64_t calc_max_float()
{
return calc_max_float<N - 1,2*val>();
}
template <const uint64_t val>
inline double calc_max_float<0, val>()
{
return (double) val;
}
然而函数的偏特化是不允许的?当我们在做的时候,为什么不做类似的事情
template <const unsigned N, const uint64_t val>
inline uint64_t calc_max_float()
{
return (N != 0) ? calc_max_float<N - 1,2*val>() : val;
}
工作?
最佳答案
#include <iostream>
template <unsigned N>
inline double calc_max_float(double val)
{
return calc_max_float<N - 1>(2.0 * val);
}
template <>
inline double calc_max_float<0>(double val)
{
return val;
}
int main() {
// 2 ^ 3
std::cout << calc_max_float<3>(1) << std::endl;
}
关于c++ - 用模板替换constexpr(用于在编译时计算常量)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452644/