【问题标题】:Templated Variables Bug With Lambdas in Visual Studio?Visual Studio 中的 Lambda 模板变量错误?
【发布时间】:2018-08-13 12:16:42
【问题描述】:

提供 variable templates 中工作正常,但在 lambdas 中它们似乎分崩离析。例如:

template <typename T>
const auto PI = std::acos(static_cast<T>(-1));

int main() {
  auto func = []() { cout << PI<float> << endl; };

  func();
}

On gcc 6.3 这个输出:

3.14159

在 Visual Studio 2017 上,此输出:

0.0

【问题讨论】:

  • 这不是一个明显的编译器错误吗?我的意思是,想象一下这是否是预期的行为颤抖
  • 有趣。已通过 MSVC 19.00.23918(Visual Studio 2017 桌面版)确认。
  • 是模板中的auto 失败,如果更改为T,它会按预期工作
  • 看起来可能是优化器问题? -Od 适合你吗?
  • @AndyG 是的,确实很棒的评论。将其放入 lambda 的捕获中也可以。

标签: c++14 visual-studio-2017 c++ lambda visual-studio-2017 c++14 variable-templates


【解决方案1】:

奇怪的错误,但它似乎有一个可靠的解决方法,适用于这种情况和related case。在这两种情况下,强制激活模板似乎都可以在 VS2017 中完成:

template <typename T>
const auto PI = std::acos(static_cast<T>(-1));

int main() 
{
  PI<float>; // <------ this
  auto func = []() { std::cout << PI<float> << std::endl; };

  func();
}

例如 GCC 6.3:https://ideone.com/9UdwBT

【讨论】:

  • 这些人试图寻求委员会将他们的编译器的功能纳入标准。
  • @bipll 希望渺茫,他们甚至无法修复他们的 bug tacker 上的 code submission format
  • 您能否也将其发布在链接的问题中。这是正确的解决方案,因为它确定了实际问题,即PI&lt;float&gt; 模板似乎没有自动初始化。那里有一个答案,它很幸运并解决了问题,但没有解决根本问题,我不愿意接受它。
  • @JonathanMee Sure thing!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多