首页  >  文章  >  后端开发  >  如何将尾随返回类型与可变参数模板函数一起使用,以推断出对不同类型的参数求和的函数的正确返回类型?

如何将尾随返回类型与可变参数模板函数一起使用,以推断出对不同类型的参数求和的函数的正确返回类型?

DDD
DDD原创
2024-11-15 02:26:02341浏览

How can trailing return types be used with variadic template functions to deduce the correct return type for a function that sums arguments of varying types?

Trailing Return Type Using Dectype with a Variadic Template Function

When attempting to create a variational template function that sums arguments of varying types and returns an appropriately typed sum, common issues arise.

Problem Formulation

A basic implementation using decltype as the trailing return type results in undefined behavior for arguments exceeding two. To avoid this, the function can be declared explicitly, but this leads to incorrect type deduction for multiple arguments.

Solution Using Custom Traits Class

To overcome these issues, a custom traits class called sum_type is utilized. It recursively calculates the return type using std::add_rvalue_reference and std::val.

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... > {};

Modified Implementation

By replacing decltype with typename sum_type::type in the trailing return type, the function correctly deduces the result type for any number of arguments:

template <class T, class... P>
auto sum(const T& t, const P&amp;... p) -&gt; typename sum_type<T,P...>::type
{
   return t + sum(p...);
}

Improved Type Deduction

Additionally, a modification to the last specialization of sum_type provides improved type deduction:

template<class T, class U, class... P> struct sum_type<T,U,P...>
: id<decltype(
      val<T>()
    + val<typename sum_type<U,P...>::type>()
)&gt;{};

This ensures that the return type matches decltype(a+(b+c)), aligning with the expected addition order.

以上是如何将尾随返回类型与可变参数模板函数一起使用,以推断出对不同类型的参数求和的函数的正确返回类型?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn