I want to return some values from a function and I want to pack it in a tuple. So I have two possibilities for function declaration:
std::tuple<bool, string, int> f()
{
...
return std::make_tuple(false, "home", 0);
}
and
std::tuple<bool, string, int> f()
{
...
return std::forward_as_tuple(false, "home", 0);
}
These functions are equivalents? Between these functions which do you prefer?
std::forward_as_tuple()
creates a tuple of references. Since you are returning a tuple<bool, string, int>
anyway, the two end up being equivalent in this case, but I think the first approach is clearer - using forward_as_tuple()
when you are not forwarding anything is confusing.
Also, as mentioned by Sebastian Redl in the comments, make_tuple()
would allow the compiler to perform copy elision - per paragraph 12.8/31 of the C++11 Standard, while forward_tuple()
would not (since what it returns does not have the same type as the function's return type).