C++ 用模板替换constexpr(用于在编译时计算常量)?
我使用C++ 用模板替换constexpr(用于在编译时计算常量)?,c++,template-meta-programming,constexpr,visual-studio-2012,C++,Template Meta Programming,Constexpr,Visual Studio 2012,我使用constexpr关键字计算编译时可以存储在浮点或双精度中的最大整数值(n是尾数中的位数,val最初为1.0): 生成此值供以下模板使用: 但是,不允许对函数进行部分专门化?既然我们这样做了,为什么不 template <const unsigned N, const uint64_t val> inline uint64_t calc_max_float() { return (N != 0) ? calc_max_float<N - 1,2*val>(
constexpr
关键字计算编译时可以存储在浮点或双精度中的最大整数值(n是尾数中的位数,val最初为1.0):
生成此值供以下模板使用:
但是,不允许对函数进行部分专门化?既然我们这样做了,为什么不
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;
}
模板
内联uint64计算最大浮点数()
{
返回值(N!=0)?计算最大浮点数():val;
}
工作?#包括
模板
内联双计算最大浮点数(双值)
{
返回计算最大浮点数(2.0*val);
}
模板
内联双计算最大浮点数(双值)
{
返回val;
}
int main(){
// 2 ^ 3
std::你能不能没有关于它如何使用的例子这很好,但它在运行时计算常量。我正在寻找一种在编译时计算它的方法。谢谢!@bhimberg信任编译器!确实如此。5E10的定时运行调用模板版本(不带constexpr
)并提取\u single()产生约34秒。我用调试版本检查了调用堆栈,发现它在运行时递归地调用了template/constepr
versions,但我猜-O3胜过了这一点?再次感谢!
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));
}
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;
}