Home > Backend Development > C++ > body text

How to Use `decltype` with Variadic Template Functions to Sum Arguments?

Mary-Kate Olsen
Release: 2024-11-13 04:48:02
Original
842 people have browsed it

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::type as shown:

#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&amp;>() + val<const U&amp;>() ), P... > {};
Copy after login

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>()
)>{};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template