8.3.5/8 Functions [dcl.fct]
规定:
[...] 函数不得返回数组或函数类型,但可以返回指向此类事物的指针或引用类型。[...]
为什么要如此明确地规定?是否存在某种语法,即使与函数指针相比,也允许返回函数本身?
我是否误解了这句话?
typedef void (*fp)();
void foo(){}
fp goo()
{
return foo; //automatically converted to function pointer
}
8.3.5/8 Functions [dcl.fct]
规定:
[...] 函数不得返回数组或函数类型,但可以返回指向此类事物的指针或引用类型。[...]
为什么要如此明确地规定?是否存在某种语法,即使与函数指针相比,也允许返回函数本身?
我是否误解了这句话?
typedef void (*fp)();
void foo(){}
fp goo()
{
return foo; //automatically converted to function pointer
}
void foo() { }
template<typename T>
T f() { return foo; }
int main(){
f<decltype(foo)>();
}
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.
是否有一些语法可以返回函数而不是函数指针?
有这样的语法吗?当然有:
using fun = int (int);
fun function_that_returns_a_function();
这段代码无法编译,因为§8.3.5/8规则禁止这样做。我不知道为什么会有这个规则 - 但请注意,“函数”类型没有任何大小,因此您不能在C++中创建函数类型的对象。
std::function<int (int)> retLambda() {
return [](int x) { return x; };
}