c++c++14variable-templates

Overhead of variable template


C++14 introduced variable templates (Variable templates).

template<class T>
constexpr T pi = T(3.1415926535897932385);  // variable template

template<class T>
T circular_area(T r) // function template
{
    return pi<T> * r * r; // pi<T> is a variable template instantiation
}

What is the overhead of using this, both in terms of the binary memory footprint and speed at runtime?


Solution

  • I'd definitely report this as a bug to the compiler maker if there is ANY difference between:

    template<class T>
    constexpr T pi = T(3.1415926535897932385);  // variable template
    
    template<class T>
    T circular_area(T r) // function template
    {
        return pi<T> * r * r; // pi<T> is a variable template instantiation
    }
    

    and

    constexpr double pi = 3.1415926535897932385;
    
    double circular_area(double r)
    {
        return pi * r * r;
    }
    

    And the same if you replace double with float.

    In general, constexpr should evaluate to the relevant constant directly in the compiled code. If it can't do that, then the compiler should give an error (because it's not a true constexpr).