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

1

u/BeaRDT Mar 30 '15

How do you plan to return an anonymous struct by using decltype?

I think of decltype as similar to auto (except for slightly different type deduction rules), ie. it uses the type you give to decltype() as if you simply typed the actual name. I might be lacking phantasy, but I fail to see how you could use that to return an anonymous struct.

1

u/acwsupremacy Mar 30 '15
struct { int i; double d; } anon {10, 3.14};

decltype(anon) my_function();

1

u/BeaRDT Mar 31 '15

Ah, that's where I was lacking phantasy. The struct is anonymous but it is known outside of the function. I always thought about returning an anonymous struct which is defined inside a function from that function, which obviously is impossible.