I know that a std::tuple
is a valid way to return multiple variables of different types from a function, as mentioned in a talk by Herb Sutter at about 1:31:00 (This code example is mine, not from the video)
auto get_tuple()
{
return std::make_tuple(1, 2);
}
then "unpacking" it with either
auto t = get_tuple();
int a = std::get<0>(t);
int b = std::get<1>(t);
or
int a;
int b;
std::tie(a, b) = get_tuple();
These methods are great, but I don't particularly like the syntax std::get
or std::tie
. I wouldn't avoid using a useful tool just because of ugly syntax (in my personal opinion), but what about doing this instead?
auto get_struct()
{
struct R
{
int a;
int b;
}
return R{1, 2};
}
This compiles for me (Visual Studio 2015) and I like the syntax of it much more. I don't want to get accused of prematurely optimizing, but I'll also mention it seems to be many times faster than a tuple. Mostly I just like the syntax though.
That said, I know that just because something compiles doesn't mean the language is meant to be used that way. I'm not exactly sure how to word this question, but basically, is this valid and defined behavior? Can I be confident that this will work on other major compilers? Frankly I was rather surprised that it would deduce the type even when that type is defined in the function itself, so I want to make sure this is okay.
This is the first time I've actually posted on this website, so sorry in advance if I did anything wrong. Please let me know if I did.
EDIT: As pointed out in responses, my claim that a local struct is many times faster than a tuple is completely wrong. I didn't do my test properly. See the replies for more, I just wanted to edit this in to make sure I don't mislead anyone.