9

provides variable templates Which work fine in , but within lambdas they seem to fall apart. For example:

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 this outputs:

3.14159

On Visual Studio 2017 this outputs:

0.0

Justin
  • 24,288
  • 12
  • 92
  • 142
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288

1 Answers1

3

Wierd bug, but it seems to have a reliable workaround, which works for both, this case and the related case. In both cases forcefully activating template seems to do the job in 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 for example: https://ideone.com/9UdwBT

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37
  • 1
    And those people tried to pursue the Committee to incorporate their compiler's features into the Standard. – bipll Mar 05 '18 at 21:14
  • 1
    @bipll Low hopes, they cannot even fix the [code submission format](https://developercommunity.visualstudio.com/content/problem/207741/template-needs-to-be-force-instantiated-vs2017-bug.html) on their bug tacker – Killzone Kid Mar 05 '18 at 21:39
  • Can you please post this in the linked question as well. It is the correct solution as it identifies the actual problem, namely that the `PI` template doesn't seem to initialize automatically. There's an answer over there, which gets lucky and solves the problem but doesn't address the underlying issue and I'm loath to accept it. – Jonathan Mee Mar 06 '18 at 13:11
  • @JonathanMee [Sure thing!](https://stackoverflow.com/a/49132236/8746007) – Killzone Kid Mar 06 '18 at 13:41