c++ 你能在函数的返回类型中定义一个特殊的匿名结构吗?

piztneat  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(83)

考虑到可以像这样创建匿名结构:

#include <iostream>

struct {
    int a;
    int b;
} my_anonymous_struct = { 2,3 };

int main() {
    std::cout << my_anonymous_struct.a << std::endl;
}

字符串
在这种情况下,是什么原因导致了错误?

#include <iostream>

struct file {
    int min;
    int max;
};

auto read_historic_file_dates(file F) -> struct { int min; int max; } {
    return { F.min, F.max };
}

int main() {
    file F = { 1, 4 };
    auto [min_date, max_date] = read_historic_file_dates(F);
}


错误数:

<source>:8:42: error: declaration of anonymous struct must be a definition
auto read_historic_file_dates(file F) -> struct { int min; int max; } {
                                         ^
<source>:15:2: error: expected a type
}
 ^
<source>:15:2: error: expected function body after function declarator


这在C++中是不可能的吗?它比必须使用std::pair更具声明性,特别是对于结构化绑定。

r9f1avp5

r9f1avp51#

不能在函数声明中声明(匿名)结构:
类型不应在返回或参数类型中定义。

  • [dcl.fct] p17
    但是你可以在函数的作用域中进行,并使用auto演绎:
auto read_historic_file_dates(file F) {
    struct { int min; int max; } res{ F.min, F.max };
    return res;
}

字符串

9rbhqvlz

9rbhqvlz2#

不,这是不可能的。你不能声明一个函数来返回一个匿名的struct,因为你不能在函数声明中定义struct
因此,您需要将此新名称命名为struct或使用现有名称,如file,这似乎适合您的情况:

auto read_historic_file_dates(file F) -> file {
    return { F.min, F.max };
}

字符串

相关问题