Search code examples
c++functiontemplatesusing

Unable to assign shorter names to C++ function templates


To improve code readability, I am trying to assign shorter names to function templates like in the example below:

#include <iostream>

template<typename T>
T func(T a, T b)
{
    return a + b;
}

int main() 
{
    using fi = func<int>;
    using fd = func<double>;

    std::cout << fi(1, 1) << std::endl;
    std::cout << fd(1.0, 1.0) << std::endl;

    return 0;
}

but upon attempting to compile, I get an error

$ g++ func.cpp -o func
func.cpp: In function ‘int main()’:
func.cpp:11:11: error: expected nested-name-specifier before ‘fi’
     using fi = func<int>;
           ^

What is the accepted way of assigning shorter names to function templates without having to rely on a preprocessor definition?


Solution

  • Using introduces a type. Function templates and their instances are not types.

    auto replacing using would make your code compile and do what you probably want. Many cpmpilers are good about inlining simple function pointer cases, so in prod it may have zero performance impact.