c++ - C++11 是否强制 pow(double, int) 使用较慢的 pow(double, double)?

标签 c++ gcc c++11 c++-standard-library

<分区>

在 C++ 03 中,使用例如std::pow(double_val, 6) 比使用 std::pow(double_val, 6.0) 快得多。

使用 C++11 编译时不再是这种情况。查看 gcc 的 libstdc++-4.8 中的 cmath header ,可以看到显式 pow(double, int) 不再存在,这种情况由以下将 int 提升为 double 的模板处理:

template<typename _Tp, typename _Up>
inline typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
pow(_Tp __x, _Up __y) {
  typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
  return std::pow(__type(__x), __type(__y));
}

这是 C++11 标准中的行为还是 future 的 libstdc++ 实现会返回到更快的方法?

其次,如果出于标准或实现原因,更快的行为不再可能,那么再次实现它的最可移植的方法是什么?我在“ext/numeric”下的 gcc stdlibc++ 中看到一个 power(...) 函数,但这被标记为一个非标准 SGI(rip) 扩展。

最佳答案

首先,是的,这种行为符合 C++11 标准(尽管不符合 C++03),该标准在第 26.8 节第 11 段中说:

Moreover, there shall be additional overloads sufficient to ensure:

  1. If any argument corresponding to a double parameter has type long double, then all arguments corresponding to double parameters are effectively cast to long double.

  2. Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double.

  3. Otherwise, all arguments corresponding to double parameters are effectively cast to float.

(除了 float-only、double-only 和 long double-only 的重载。)

所以实现实际上必须将该整数参数转换为double,我认为符合标准的库不可能提供更快的std::pow 用于整数幂,除了可能检查 double 参数的完整性(这是一个词吗?)并在这种情况下使用特殊路径。

为了提供一种独立于平台的更快的方式,我想到的唯一一件事就是编写一个自定义包装器,如果它存在的话,委托(delegate)给这个非标准的power。除此之外,我不知道如何在不编写自己的实现的情况下将这种行为再次注入(inject) std::pow

编辑: 然而,在查看 this answer 时只要它的行为与 std::pow(double(x), double(y)) 完全一样,一个实现确实有可能仍然为整数幂提供优化的重载。所以有可能实现提供更快的版本,但我不会像你在 C++03 中所做的那样指望它(恕我直言,它甚至是标准的一部分,但我可能是错的) .

关于c++ - C++11 是否强制 pow(double, int) 使用较慢的 pow(double, double)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18873123/

相关文章:

C++模板类问题

java - 在排序数组 X 中搜索第一个索引 i 使得 X[i] >= a

c - erl_interface 链接器错误

gcc - 仅编译thumb1

c++ - 为什么禁止对位域的非常量引用?

c++ - 我如何将 C++ 与 VALA 混合使用

c++ - 共享对象工厂的设计模式

gcc - 在 ubuntu 中安装 gcc 更新版本 4.6

c++ - 需要将 for 循环的上限保存在额外的变量中吗?

c++ - 如何合并两个包含 std::unique_ptr 的 vector ?