c++lambdavisual-studio-2017c++14variable-templates

Templated Variables Bug With Lambdas in Visual Studio?


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


Solution

  • 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