首頁  >  文章  >  後端開發  >  如何將尾隨返回類型與可變參數模板函數一起使用,以推斷出對不同類型的參數求和的函數的正確返回類型?

如何將尾隨返回類型與可變參數模板函數一起使用,以推斷出對不同類型的參數求和的函數的正確返回類型?

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