C++ 不允许从函数返回函数。我怎么能?
C++ 不允许从函数返回函数。我怎么能?,c++,function,function-pointers,language-lawyer,C++,Function,Function Pointers,Language Lawyer,8.3.5/8函数[dcl.fct]表示 […]函数的返回类型不应为 键入数组或函数,尽管它们可能有一个类型指针或引用的返回类型。[……] 为什么规则如此明确?是否存在允许返回函数而不是函数指针的语法 我是不是错过了翻译这句话 typedef void (*fp)(); void foo(){} fp goo() { return foo; //automatically converted to function pointer } 我知道这可能不能完全回答你的问题,但它只能部分回
8.3.5/8函数[dcl.fct]
表示
[…]函数的返回类型不应为
键入数组或函数,尽管它们可能有一个类型指针或引用的返回类型。[……]
为什么规则如此明确?是否存在允许返回函数而不是函数指针的语法
我是不是错过了翻译这句话
typedef void (*fp)();
void foo(){}
fp goo()
{
return foo; //automatically converted to function pointer
}
我知道这可能不能完全回答你的问题,但它只能部分回答 您可以从另一个函数返回一个函数(lambda就是这样的函数)
std::函数retLambda(){
return[](int x){return x;};
}
是否存在允许返回函数而不是函数指针的语法
语法?当然有:
using fun = int (int);
fun function_that_returns_a_function();
因为§8.3.5/8中的规则禁止它,所以它不能编译。我不知道这个规则为什么具体存在——但是考虑到“函数”的类型没有任何大小,所以不能在C++中创建函数类型的对象。 这是一个试图返回函数的函数席:
void foo() { }
template<typename T>
T f() { return foo; }
int main(){
f<decltype(foo)>();
}
void foo(){}
模板
tf(){return foo;}
int main(){
f();
}
这是我从Clang 3.2中得到的错误:
Compilation finished with errors:
source.cpp:7:5: error: no matching function for call to 'f'
f<decltype(foo)>();
^~~~~~~~~~~~~~~~
source.cpp:4:3: note: candidate template ignored: substitution failure
[with T = void ()]: function cannot return function type 'void ()'
T f() { return foo; }
~ ^
1 error generated.
编译已完成,但出现错误:
source.cpp:7:5:错误:没有用于调用“f”的匹配函数
f();
^~~~~~~~~~~~~~~~
source.cpp:4:3:注意:已忽略候选模板:替换失败
[使用T=void()]:函数无法返回函数类型'void()'
tf(){return foo;}
~ ^
生成1个错误。
@B.Nadolson,仅计为无效转换。“自动转换为函数指针”。那么它不是一个函数;)从技术上讲,lambda不是函数,它们是函子+1:的实例。而且,这只是一个罕见的例子,其中C++使事情变得清晰明了,而不是让我们从语法和其他各种规则(例如非复制性)中获得它。赞美他@光明赛道:的确如此。我经常觉得从标准中推导规则就像证明一个数论定理。在这种情况下不行;有趣的是,很少有人会从一个发出警报的OP中生成一个SO问题。
Compilation finished with errors:
source.cpp:7:5: error: no matching function for call to 'f'
f<decltype(foo)>();
^~~~~~~~~~~~~~~~
source.cpp:4:3: note: candidate template ignored: substitution failure
[with T = void ()]: function cannot return function type 'void ()'
T f() { return foo; }
~ ^
1 error generated.