c++visual-studio-2017c++14divisionvariable-templates

Division in Variable Template Returns Zero in Visual Studio 2017


This is probably a bug related to this question: Templated Variables Bug With Lambdas in Visual Studio? And as mentioned in the comments there seems to be optimizer related.


Division in the definition of a variable template seems to have a bug in Visual Studio 2017. So this code for example:

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

template <typename T>
const T ONE_EIGHTY = 180;

template <typename T>
const T DEG_TO_RAD = PI<T> / ONE_EIGHTY<T>;

int main() {
    cout << DEG_TO_RAD<float> << endl;
}

On gcc 6.3 this outputs:

0.0174533

On Visual Studio 2017 this outputs:

0.0

I'm assuming this is another Visual Studio bug? Is there a workaround here?


Solution

  • Posting a workaround here at the request of @JonathanMee as it also works for the similar problem reported by him earlier. Seems to be connected with some sort of bug in latest VS2017 that prevents template from activating automatically and needs a force activation:

    template <typename T>
    const T PI = std::acos(static_cast<T>(-1));
    
    template <typename T>
    const T ONE_EIGHTY = 180;
    
    template <typename T>
    const T DEG_TO_RAD = PI<T> / ONE_EIGHTY<T>;
    
    int main() 
    {
        PI<float>; // <---- workaround
        std::cout << DEG_TO_RAD<float> << std::endl;
    }
    

    Here is a bug ticket filed with Microsoft: https://developercommunity.visualstudio.com/content/problem/207741/template-needs-to-be-force-instantiated-vs2017-bug.html