我想以这种方式定义自动返回类型的函数,如果我包含标头,我可以从多个.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();
}
所有文件complate我仍然有错误:
Error:在扣除“自动”之前使用“ auto f()”
auto fu = f();
不幸的是,C ++不起作用。当您在C ++中调用函数时:
auto fu=f();
auto
但是这个“以后”永远不会到来。如果编译器所看到的所有内容都是
auto
返回类型,则编译器无法确定函数的实际返回类型,因此,该程序是不形成的,您会遇到编译错误。这是C ++的基本方面,没有解决方法。
填写标题。将
f
的定义放在
模块中。
// head.cpp
export module head;
export auto f()
{
// whatever
}
然后在另一个tu中导入该模块。
// main.cpp
import head;
int main()
{
... f() ... // whatever
}
f
的类型在
main.cpp
中很神奇。