Reputation: 1141
What I am trying to achieve is mainly returning an unnamed struct from a function in C++11. In C++14, I can do this by defining the function inline and having auto
as return type, like this:
auto func()
{
struct
{
int member;
} ret;
// set ret.member
return ret;
}
However, C++11 doesn't support deducing the return type of a normal (non-lambda) function, and this only works in C++14 when the definition is done inline.
I tried the following two variations of declaring the struct in the function declaration:
auto func() -> struct { int member; };
struct { int member; } func();
Is this simply impossible to do with C++11? If so, does someone know whether this was disallowed on purpose or just nobody thought of this new use of automatically deduced types (because this only works with the functions return value being assigned to an auto
variable)?
And finally, is there any other way to achieve something similar to this? I am aware of std::tuple
, but I want to name the values; and in my use case the struct type is definitely only useful as return type of this one function, so why name it?
Upvotes: 8
Views: 709
Reputation: 137330
[dcl.fct]/p11:
Types shall not be defined in return or parameter types.
This is not new in C++11, as far as I know.
Upvotes: 4
Reputation:
A class-specifier consists of a class-head-name and { }
. Once the closing brace is encountered, the class is defined. If the class-head-name is omitted, the class is unnamed (§9). A type-specifier can have a class-specifier, but trailing-type-specifier can't (only simple-type-specifier, elaborated-type-specifier, typename-specifier and cv-qualifier are allowed, §7.1.6). For this reason, I believe that it's not possible to put the definition of a class in a trailing-return-type.
Source: N4140
Upvotes: 2