Introduced in C 14, the decltype(auto) idiom allows auto declarations to use the decltype rules on the given expression. While its primary use is for a function's return type deduction, there are other valuable applications.
In generic code, decltype(auto) enables perfect forwarding of a return type without knowing its underlying type. This is particularly useful for generic functions:
template<class Fun, class... Args> decltype(auto) Example(Fun fun, Args&&... args) { return fun(std::forward<Args>(args)...); }
decltype(auto) can also delay return type deduction in recursive templates, preventing infinite recursion. For example:
template<int i> struct Int {}; constexpr auto iter(Int<0>) -> Int<0>; template<int i> constexpr auto iter(Int<i>) -> decltype(auto) { return iter(Int<i-1>{}); }
Beyond these primary applications, decltype(auto) has various other uses, as outlined in the C draft Standard (N3936):
Variable initialization:
decltype(auto) x3d = i; // decltype(x3d) is int
Pointer declaration:
decltype(auto)*x7d = &i; // decltype(x7d) is int*
The above is the detailed content of What are the Applications of `decltype(auto)` in C ?. For more information, please follow other related articles on the PHP Chinese website!