C++函数返回函数

标签 c++ c++11 standards language-lawyer

标准中哪些地方不允许函数返回函数?我知道它们在概念上很荒谬,但在我看来,语法允许它们。根据此网页,“noptr-declarator [is] any valid declarator”将包含函数的声明符:

int f()();

关于语法。

在我看来,如 [dcl.decl] 中所述的语法允许

int f(char)(double)

可以解释为函数 f 接受一个 char 并返回一个函数与 int g(double)具有相同的签名。

1    declarator:
2       ptr-declarator
3       noptr-declarator parameters-and-qualifiers trailing-return-type
4    ptr-declarator:
5        noptr-declarator
6        ptr-operator ptr-declarator
7    noptr-declarator:
8        declarator-id attribute-specifier-seq opt
9        noptr-declarator parameters-and-qualifiers
10       noptr-declarator [ constant-expression opt ] attribute-specifier-seq opt
11       ( ptr-declarator )
12    parameters-and-qualifiers:
13       ( parameter-declaration-clause ) cv-qualifier-seqAfter

粗略地说,之后 1->2, 2=4, 4->6, 4->6 你应该有 ptr-operator ptr-operator ptr-operator 然后,使用 4->5, 5=7, 7->8 作为第一个声明符;对第二个和第三个声明符使用 4->5, 5=7, 7->9。

最佳答案

来自 [dcl.fct],非常明确:

Functions shall not have a return type of type array or function, although they may have a return type of type pointer or reference to such things. There shall be no arrays of functions, although there can be arrays of pointers to functions.

使用 C++11,您可能只想:

std::function<int()> f();
std::function<int(double)> f(char);

关于 C++ 语法存在一些混淆。语句int f(char)(double); 可以按照语法进行解析。这是一个解析树:

grammar

此外,基于 [dcl.fct]/1 的这种解析甚至是有意义的:

In a declaration T D where D has the form
    D1 ( parameter-declaration-clause ) cv-qualifier-seqopt
        ref-qualifieropt exception-specificationopt attribute-specifier-seqopt
and the type of the contained declarator-id in the declaration T D1 is “derived-declarator-type-list T”, the type of the declarator-id in D is “derived-declarator-type-list function of (parameter-declaration-clause ) cv-qualifier-seqopt ref-qualifieropt returning T”.

在这个例子中 T == int, D == f(char)(double), D1 == f(char) . T D1 (int f(char))中declarator-id的类型是“(char)返回int的函数”。所以 derived-declarator-type-list 是“(char) 返回函数”。因此,f 的类型将被解读为“(char) 函数返回函数(double) 返回 int”。

这最终是无稽之谈,因为这是明确不允许的声明符形式。但不是由语法。

关于C++函数返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31387238/

相关文章:

c++ - 如何在 Visual Studio 2012 中向编译的 dll 文件添加属性?

c++ - 使用 Boost::asio 触发写入

c++ - 声明 SID Windows c++

c++ - 在模板链表中没有调用查找的匹配函数

javascript - 为什么 `eval` 对非字符串有效?

带有描述的 C++ 智能感知

c++ - 为 UDF std::unordered_map 提供 ":"运算符?

c++ - 如何包含 DLL 的类?

sql - 是否有适用于所有数据库的标准sql

php - 退出函数的标准