【问题标题】:Replace constexpr (used to calculate constant at compile time) with template?用模板替换 constexpr (用于在编译时计算常量)?
【发布时间】: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


【解决方案1】:
#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;
}

【讨论】:

  • 这很好,但它会在运行时计算常数。我正在寻找一种在编译时计算它的方法。谢谢!
  • @bhimberg 相信编译器!
  • 确实如此。模板版本(没有constexpr)和 extract_single() 的 5E10 调用的定时运行产生约 34 秒。我用调试版本检查了调用堆栈,发现它在运行时递归地调用了模板/constexpr 版本,但我猜 -O3 胜过那?再次感谢!
猜你喜欢
  • 2012-08-27
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 2013-11-18
  • 2016-06-05
相关资源
最近更新 更多