简体   繁体   English

可变参数函数-确定返回类型

[英]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 . 前两个参数的类型为int Therefore in the trailing return type, decltype(a + b) is int , so the result is converted to int - and truncated. 因此,在尾随返回类型中, decltype(a + b)int ,因此结果将转换为int并被截断。

Use std::common_type : 使用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: 使用C ++ 14,虽然可以进行返回类型推导:

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. 也许增加衰减。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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