r/cpp • • Mar 30 '15

Simple Question

So I was thinking the other day, and I came up with an idea that I decided to try... a function returning an anonymous struct!

I tried it, and lo and behold, it doesn't compile. A closer look reveals that the Standard specifically disallows defining new types as the return type of a function definition! Though it does appear that I can return an anonymous struct using decltype, that is even more code than simply defining a new type name.

My Simple Question is... why? What reason did the standards committee have to explicitly disallow this? Is this a case of them trying to save users from their own stupidity, or is this technically infeasible somehow?

1 Upvotes

20 comments sorted by

View all comments

6

u/tongari95 Mar 31 '15

I'm not sure what you want but this works for me:

auto make_anon(int i)
{
    struct
    {
        int val;
    } ret{ i };
    return ret;
}
...
std::cout << make_anon(555).val;

1

u/Gotebe Mar 31 '15

You devious bastard! :-)