Can you define an ad hoc anonymous struct in the return type of a function?

203 views Asked by At

Considering it is possible to create anonymous structs like this:

#include <iostream>

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

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

What causes errors to arise in this case?

#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);
}

Errors:

<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

Is this not possible in C++ (yet)? It would be more declarative than having to use std::pair, especially for structured bindings.

2

There are 2 answers

3
Jarod42 On BEST ANSWER

You cannot declare the (anonymous) struct in the declaration of the function:

Types shall not be defined in return or parameter types.

- [dcl.fct] p17

But you can do it in the scope of the function, and use auto deduction:

auto read_historic_file_dates(file F) {
    struct { int min; int max; } res{ F.min, F.max };
    return res;
}
0
Ted Lyngmo On

No, it's not possible. You can't declare a function to return an anonymous struct since you can't define the struct in the function declaration.

So, you need to name this new struct or use an existing name, like file that seems to fit in your case:

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