简体   繁体   中英

Variadic function - determining return type

I'm playing with variadic templates and i'm stuck with the following:

template <class T1, class T2>
auto sum(T1 a, T2 b) ->decltype(a + b){
    return a + b;
}
template <class T1, class T2, class... T3>
auto sum(T1 a, T2 b, T3... tail) ->decltype(a + b){
    return a + sum(b, tail...);
}

Function calls:

cout << sum(1, 2, 3, 4) << endl;    // 10 - OK
cout << sum(1.5, 2, 3, 4) << endl;  // 10.5 - OK
cout << sum(1, 2, 3.5, 4) << endl;  // 10 !! wrong result

What am I doing wrong here?

sum(1, 2, 3.5, 4)

The first two arguments are of type int . Therefore in the trailing return type, decltype(a + b) is int , so the result is converted to int - and truncated.

Use std::common_type :

template <class T1, class T2, class... T3>
typename std::common_type<T1, T2, T3...>::type
  sum(T1 a, T2 b, T3... tail) 
{
    return a + sum(b, tail...);
}

Note that

template <class T1, class T2, class... T3>
auto sum(T1 a, T2 b, T3... tail) ->decltype(a + sum(b, tail...))

Does not work as this second template isn't known in the trailing-return-type, only the first one. With C++14, return type deduction is possible though:

template <class T1, class T2, class... T3>
auto sum(T1 a, T2 b, T3... tail)
{
    return a + sum(b, tail...);
}
namespace details{
  template<template<class,class>class binary_result, class T, class...Ts>
  struct nary_result{using type=T};
  template<template<class,class>class binary_result, class T0, class T1, class...Ts>
  struct nary_result<binary_result, T0,T1,Ts...>:
    nary_result<binary_result,binary_result<T0,T1>,Ts...>
  {};
}
template<template<class,class>class binary_result, class...Ts>
using nary_result=typename details::nary_result<binary_result,Ts...>::type;

template<class Lhs, class Rhs>
using binary_sum_result = decltype(std::declval<Lhs>()+std::declval<Rhs>());

template<class...Ts>
using sum_result=nary_result<binary_sum_result,Ts...>;

should do the trick.

Maybe add a decay.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM