考虑到可以像这样创建匿名结构:
#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
更具声明性,特别是对于结构化绑定。
2条答案
按热度按时间r9f1avp51#
不能在函数声明中声明(匿名)结构:
类型不应在返回或参数类型中定义。
但是你可以在函数的作用域中进行,并使用
auto
演绎:字符串
9rbhqvlz2#
不,这是不可能的。你不能声明一个函数来返回一个匿名的
struct
,因为你不能在函数声明中定义struct
。因此,您需要将此新名称命名为
struct
或使用现有名称,如file
,这似乎适合您的情况:字符串