c++structured-bindingsanonymous-struct

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


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.


Solution

  • 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;
    }