How to include functions with auto return type from header file into multiple cpp files

I want to define a function of auto return type in such a way, that I can call it from multiple .cpp files if I include the header. I have 4 files

head.hpp – where the function is

#ifndef HEAD_HPP
#define HEAD_HPP 

auto f();

#endif

head.cpp – where the function is declared

#include "head.hpp"

auto f(){
    return [](){
        return 10;
    };
}

test1.cpp – where it is used

#include "head.hpp"
int foo(){
    auto func = f();
    return f();
}

main.cpp – where it is used as well

#include "head.hpp"
int foo();
int main(){
    auto fu = f();

    return fu() + 5 + foo();
}

All files are compiled together I still get the error:

error: use of ‘auto f()’ before deduction of ‘auto’

auto fu = f();

Answer

Unfortunately, C++ does not work this way.

When you call a function in C++:

auto fu=f();

The compiler must know the discrete type that the function actually returns. auto is not a real type. It is just a placeholder for a type to be figured out later.

But this “later” never comes. If all that the compiler sees is an auto return type, the compiler cannot determine the function’s actual return type, and, therefore, the program is ill-formed, and you get a compilation error.

This is a fundamental aspect to C++, and there are no workarounds.