我想以这样的方式定义一个自动返回类型的函数,如果我包含标题,我可以从多个 .cpp 文件中调用它。我有 4 个文件head.hpp
- 函数在哪里
#ifndef HEAD_HPP
#define HEAD_HPP
auto f();
#endif
head.cpp
- 函数声明的地方#include "head.hpp"
auto f(){
return [](){
return 10;
};
}
test1.cpp
- 在哪里使用#include "head.hpp"
int foo(){
auto func = f();
return f();
}
main.cpp
- 也用在哪里
#include "head.hpp"
int foo();
int main(){
auto fu = f();
return fu() + 5 + foo();
}
所有文件都是一起编译我仍然收到错误:
error: use of ‘auto f()’ before deduction of ‘auto’
auto fu = f();
最佳答案
不幸的是,C++ 不能以这种方式工作。
在 C++ 中调用函数时:
auto fu=f();
编译器必须知道函数实际返回的离散类型。
auto
不是真正的类型。它只是稍后要弄清楚的类型的占位符。但是这个“后来”永远不会到来。如果编译器看到的只是
auto
返回类型,编译器无法确定函数的实际返回类型,因此,程序格式错误,您会收到编译错误。这是 C++ 的一个基本方面,没有变通方法。
关于c++ - 如何将具有自动返回类型的函数从头文件包含到多个 cpp 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59501389/