Trailing Return Type Using decltype with a Variadic Template Function
This inquiry seeks to construct a basic adder that calculates the sum of any number of arguments with the appropriate return type. However, the current implementation exhibits limitations with multiple arguments. This article investigates the underlying issue and explores a potential workaround.
The initial implementation utilizes the trailing return type syntax to simplify the summation function. However, for arguments exceeding two, compilation errors arise, indicating that the function is undefined. This anomaly stems from the fact that the variadic function template is declared after its return type is specified. As a result, the decltype() expression cannot refer to the variadic function template itself.
While C 0x allows for recursive calls in the ->decltype(expr) part, it may not support specific scenarios like this. To address this, a custom traits class, sum_type, is introduced as a workaround. It enables the replacement of decltype with typename sum_type
However, the initial implementation returns decltype((a b) c) instead of the expected decltype(a (b c)). To rectify this, the sum_type specialization can be modified to ensure the desired order of operations, leading to the final solution.
The above is the detailed content of How to Achieve Trailing Return Type with a Variadic Template Function for Summation?. For more information, please follow other related articles on the PHP Chinese website!