Arrow Operator in Function Headers
In C 11 and later, two syntaxes exist for function declarations:
Traditional Syntax:
return-type identifier(argument-declarations...)
Modern Syntax:
auto identifier(argument-declarations...) -> return_type
Both syntaxes are equivalent. However, the modern syntax provides a convenient way to deduce the return type from the argument types. This is particularly useful when using the decltype specifier, which enables you to describe the type of an expression.
In previous C versions, you would write:
template <typename T1, typename T2> decltype(a + b) compose(T1 a, T2 b);
However, the compiler would not know what a and b are when trying to determine the return type.
To resolve this, you could use declval:
template <typename T1, typename T2> decltype(std::declval<T1>() + std::declval<T2>()) compose(T1 a, T2 b);
However, this becomes verbose. Instead, the modern syntax allows you to write:
template <typename T1, typename T2> auto compose(T1 a, T2 b) -> decltype(a + b);
This syntax is more concise and maintains the same scoping rules.
C 14 Update:
C 14 allows the use of the following syntax:
auto identifier(argument-declarations...)
as long as the function is fully defined before use and all return statements deduce the same type.
Use Cases:
The arrow operator (->) syntax remains useful for public functions declared in header files where you want to hide the implementation in the source file. This is especially relevant for template functions or specialized concrete types derived through template metaprogramming.
The above is the detailed content of When Should You Use the Arrow Operator in C Function Headers?. For more information, please follow other related articles on the PHP Chinese website!