Константа с плавающей точкой оценивается в 0 при использовании шаблона переменной - PullRequest
2 голосов
/ 28 апреля 2020

В следующем источнике почему константа DEG_TO_RAD_B оценивается как 0?

/// @file Main.cpp

// Includes

#include <cmath>
#include <iostream>


// Constant definitions

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

const float DEG_TO_RAD_A                // good - evaluates to 0.0174533
    = std::acos(-float(1)) / 180.0f;

const float DEG_TO_RAD_B                //  bad - evaluates to 0
    = PI<float> / 180.0f;


/// Process entry point

int main()
{
    float deg_to_rad = PI<float> / 180.0f;

    std::cout << "PI:           " << PI<float>    << std::endl; // good - 3.14159
    std::cout << "deg_to_rad:   " << deg_to_rad   << std::endl; // good - 0.0174533
    std::cout << "DEG_TO_RAD_A: " << DEG_TO_RAD_A << std::endl; // good - 0.0174533
    std::cout << "DEG_TO_RAD_B: " << DEG_TO_RAD_B << std::endl; //  bad - 0

    return 0;
}

Вывод с использованием Visual Studio Community 2019 версии 16.4.5:

PI:           3.14159
deg_to_rad:   0.0174533
DEG_TO_RAD_A: 0.0174533
DEG_TO_RAD_B: 0

_MSC_VER : 1924
_MSC_FULL_VER : 192428316
_MSC_BUILD : 0
_MSVC_LANG : C++17

Не получает никаких предупреждений компилятора. Один и тот же вывод независимо от настроек конфигурации x86 / x64 / debug / release.

...