Reputation: 17266
It can be quite useful to leave the return type of a C++ function unspecified when the return type is unambiguous.
This can be done in modern C++ using the auto
keyword.
For example, the function below has an unambiguous return type. There is no real need to specify the type more than once.
auto example_function() {
// This could also be written as
//
// `return 1;`
//
// 1 is of type `int`.
// It can be made even more explicit with a type cast,
// if you so desire, or provide a variable with an explicit
// type as shown below.
int i = 1;
return i;
}
It is preferable to leave the compiler to deduce the return type in such simple cases. If the return type is changed, it only needs to be changed in a single place, rather than multiple places.
This seems to work fine, provided that the function with the deduced (auto
) return type is called from within the same .cpp
file. (In other words, it is used from within the same translation unit / object code file.)
What I find is that if I try to move such a function into its own .cpp
file, the type deduction no longer works.
g++-14 -std=c++23
provides the following error message:
error: use of `auto create_server_fd(int)` before deduction of `auto`
Here is the relevant function, which is in a file called create_server_fd.cpp
.
#include "create_server_fd.hpp"
auto create_server_fd(const int server_port) {
// do some work to create `fd`
int fd = 10; // example
return fd;
}
The header file contains only the forward declaration of the function.
I would expect this to compile, because the compiler should be able to figure out what type auto
should take in the return value. Indeed, it does appear as if this source file has compiled successfully.
I believe that the error is related to the use of this function, not the definition of it.
// main.cpp
#include "create_server_fd.hpp"
int main() {
const auto server_fd = create_server_fd(100); // example
}
Should this be expected to work?
If not, why can't the compiler compile this code? Can the compiler not inspect the object code create from compiling create_server_fd.cpp
and copy across the return type?
If this can't be made to work, what is the most sensible thing to do to fix this?
Upvotes: 0
Views: 70