【问题标题】:Intel icpc and C++14: How to constexpr std::complex?英特尔 icpc 和 C++14:如何 constexpr std::complex?
【发布时间】:2017-04-07 03:47:46
【问题描述】:

在我的计算中,我使用虚数单位,我认为编译器应该能够在编译时通过减少类似的东西来简化这些操作

a + i b --> std::complex(a,b)

当然,以上是简化的,我的表达通常看起来更复杂(双关语)。

在 C++14 中,我可以使用复杂的文字,而在 C++11 中,我使用的是 constexpr std::complex 变量。但是,这两种方法都因英特尔 C++ 编译器 icpc 而失败,错误消息在源代码中显示为 cmets。

如何解决这些故障?

#include <complex>

auto test1(double a, double b)
{
  // error #1909: complex integral types are not supported
  using namespace std::complex_literals;
  auto z = a + 1i*b;
  return z;
}

auto test2(double a, double b)
{
  // error: calling the default constructor for "std::complex<double>" does not produce a constant value
  constexpr std::complex<double> I(0,1);
  auto z = a + I*b;
  return z;
}

auto test3(double a, double b)
{
  // Can this be optimized as good as the others?
  std::complex<double> I(0,1);
  auto z = a + I*b;
  return z;
}

额外问题: 为什么 test2 被优化掉并被跳转到 test3 所取代? (见https://godbolt.org/g/pW1JZ8

【问题讨论】:

  • test2 优化仅仅是因为允许编译器发出这样的代码;它遵循as-if规则

标签: c++ c++14 complex-numbers icc


【解决方案1】:

复杂文字的错误是不言自明的。我手头的intel编译器版本(16.0.3)都不支持。

说到第二个错误,我想说它主要取决于您使用的 GCC 标准库版本,因为 icpc 没有提供(完整的)标准库。我已经安装了 GCC 5.4,你的 test2 函数编译正确。

应该有所不同的是std::complex的构造函数是否被注释为constexpr。在 GCC 5.4 中是:

       _GLIBCXX_CONSTEXPR complex(const _Tp& __r = _Tp(), const _Tp& __i = _Tp())
  : _M_real(__r), _M_imag(__i) { }

【讨论】:

  • 我的代码使用 GCC 和 Clang 在同一台机器上编译,它们都使用 stdlibc++,这是 ICC 显然也使用的一个,但它在 ICC 中不起作用。
  • @HenriMenke 你在使用-std=c++14 标志吗?这对我有用:echo "#include &lt;complex&gt;" &gt; foo.cppecho "auto test2(double a, double b) { constexpr std::complex&lt;double&gt; I(0,1); return a + I*b; }" &gt;&gt; foo.cppicpc -std=c++14 -c foo.cpp
  • 是的,我正在使用 -std=c++14 和 ICC 17.0.2。
  • @HenriMenke 我明白了。似乎 libstdc++ 对std::complex&lt;double&gt; 有一个特殊化,icpc 17 不喜欢 constexpr-evaluation,但它确实适用于 icpc 16。无论如何,正如您所指出的,编译器应该非常擅长优化这些常量值。
猜你喜欢
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多