c++templatesc++14type-deductionvariable-templates

Can variable templates infer type?


introduced variable templates so I can do:

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

Now, when using this variable can the type be deduced? For example:

const auto TWO_PI = 2.0F * PI;

Here I would expect PI<float> it seems like the compiler should be able to deduce that. Why won't the compiler select this for me?


Solution

  • No, it's not possible.*


    *There is an ugly alternative, but I'd advise against using it:

    template <typename T> const auto pi = std::acos(static_cast<T>(-1));
    
    struct auto_pi_t {} auto_pi;
    
    template <typename T> auto operator+(T a, auto_pi_t)
    {return a + pi<std::conditional_t<std::is_floating_point_v<T>, T, double>>;}
    template <typename T> auto operator+(auto_pi_t, T a)
    {return pi<std::conditional_t<std::is_floating_point_v<T>, T, double>> + a;}
    // For similar overloads for all plausible operators.