I am confused with when and why to use auto or decltype(auto) on the return types of functions.
I thought auto by itself always made a copy of the stuff at its right side. I thought auto& returns an lreference to the stuff at its right and auto&& returned an rreference to the stuf at its right.
But this code leaves me perplexed:
1 2 3 4
Customer c{ "Tim", "Stark", 42 };
auto [f, l, a] = c;
auto [ff, ll, aa] = getCustomer();
since f,ff,l and ll have type std::string&& while a and aa have type int&!!
To be complete, I am including the relevant code beneath this in case it helps figure out what is going on:
I thought auto& returns an lreference to the stuff at its right and auto&& returned an rreference to the stuf at its right.
Simply:
But here, you have to specify the & or && along with auto. What if you're coding a perfect forwarding function and you don't know the arguments? This is where decltype(auto) comes in which was introduced with C++14
For info about decltype() see https://en.cppreference.com/w/cpp/language/decltype. This gives the required type based on the specified expression. But if the expression is to be determined, then decltype(auto) is used.
auto follows the template argument deduction rules and is always an object type. decltype(auto) follows the decltype rules for deducing reference types based on value categories.
No your question is not too vague or general. I think it is a good question, I am not the right person to answer it.
Sometimes it may take a day or 2 to see a responce. I have seen some take even longer. Other times it may just take bumping the post to the top of the stack before someone notices.
As I look over your code I have to ask what C++ standard is it written for. Some of the code is beyond what I know and I will have to research "decltype(auto)".
In this situation the compiler is being asked to provide types from withing a Customer for the various members. It is a simplification of something like:
1 2 3
auto f = c.name;
auto l = c.last;
auto a = c.age;
It is also used with tuples (and I vaguely remember reading a discussion where the inspiration came from the syntax for getting the various entries from a tuple).