Home > Article > Backend Development > How to Use `decltype` with Variadic Template Functions to Sum Arguments?
Using decltype with Variadic Template Functions
When attempting to write a variadic template function that returns a sum with an appropriate type using decltype, it is possible to encounter some unexpected issues.
The Problem
Initially, a function is declared without a trailing return type. However, when passed multiple arguments, the compiler interprets the function as undefined. Declaring the function with a trailing return type resolves the issue for more than two arguments but results in incorrect return types for arguments of different types.
The Issue
decltype is unable to deduce the type of t sum(p...) for more than two arguments because the variadic function template is only declared after the return type is specified.
The Workaround
To avoid this recursive call in decltype, a custom traits class can be employed. The sum_type class determines the type of the sum for multiple arguments without the need for recursive deduction.
Updated Code
Replace decltype in your program with typename sum_type
#include <iostream> #include <type_traits> using namespace std; template<class T> typename std::add_rvalue_reference<T>::type val(); template<class T> struct id{typedef T type;}; template<class T, class... P> struct sum_type; template<class T> struct sum_type<T> : id<T> {}; template<class T, class U, class... P> struct sum_type<T,U,P...> : sum_type< decltype( val<const T&>() + val<const U&>() ), P... > {};
This method returns decltype((a b) c) instead of decltype(a (b c)). For a more precise result of decltype(a (b c)), modify the last specialization as follows:
template<class T, class U, class... P> struct sum_type<T,U,P...> : id<decltype( val<T>() + val<typename sum_type<U,P...>::type>() )>{};
The above is the detailed content of How to Use `decltype` with Variadic Template Functions to Sum Arguments?. For more information, please follow other related articles on the PHP Chinese website!