The introduction of decltype(auto) in C 14 brought a transformative feature that extended the possibilities of type deduction. Beyond its primary purpose of allowing auto declarations to conform to decltype rules, decltype(auto) offers a myriad of other valuable applications.
In generic code, flawlessly forwarding return types is crucial. Unlike non-generic code, where return types can be manually specified to obtain a reference type, decltype(auto) provides the flexibility to forward return types, regardless of their reference type, without any prior knowledge.
template
decltype(auto) Example(Fun fun, Args&&... args)
{
return fun(std::forward<Args>(args)...);
}
In recursive templates, infinite recursion can occur during template instantiation if the return type is specified based on a previous iteration. By utilizing decltype(auto), the return type deduction is postponed until template instantiation is finished, ensuring proper type resolution.
template
struct Int {};
constexpr auto iter(Int<0>) -> Int<0>;
template
constexpr auto iter(Int) -> decltype(auto)
{ return iter(Int
int main() { decltype(iter(Int<10>{})) a; }
The versatility of decltype(auto) extends to other contexts as well, as outlined in the C draft standard (N3936):
The above is the detailed content of How Does `decltype(auto)` Expand C Type Deduction Capabilities?. For more information, please follow other related articles on the PHP Chinese website!