【发布时间】:2013-08-29 10:41:32
【问题描述】:
我使用constexpr 关键字来计算编译时能够存储在浮点数或双精度中的最大整数值(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;
}
工作?
【问题讨论】:
-
你没有使用它的例子
标签: c++ template-meta-programming constexpr visual-studio-2012