c++templatesc++17template-instantiation

Explicit instantiation of function template with `using` or otherwise


using for class templates works like a charm

 template<class T,int N>
 struct VecNT{ T arr[N]; };

 using Vec5d = VecNT<double,5>;     // doing great job!

but it seems it does not work for functions at all

 template<class T,int N>
 T sumNT(T* xs){ T sum=0; for(int i=0;i<N;i++){sum+=xs[i];}; return sum; };

 using sum5d = sumNT<double,5>;  
    // ERROR: sumNT<double,5> does not name a type

 using sum5d(double* xs) = sumNT<double,5>(T* xs);
    // ERROR: expected nest-name-specifier before 'sum5d'

So how to make sum5d as an specialized/instantiated alias for sumNT<double,5> ?


Solution

  • You can just declare a function pointer for your alias:

    template<class T,int N>
    T sumNT(T* xs){ T sum=0; for(int i=0;i<N;i++){sum+=xs[i];}; return sum; };
    
    constexpr auto sum5d = &sumNT<double,5>;  
    
    int main()
    {
        double d[5];
        sum5d(d);
    }
    

    GCC and Clang manage to optimise away the function pointer and call the original function directly, MSVC doesn't: https://godbolt.org/z/1_fs83