Использование std :: initializer_list в функции шаблонаariadi c - PullRequest
0 голосов
/ 09 мая 2020

Я не могу понять, как работает приведенный ниже фрагмент кода. Особенно std::initializer_list использование.

template<typename ... T>
auto sum(T ... t)
{
   typename std::common_type<T...>::type result{};
   std::initializer_list<int>{ (result += t, 0) ... };

   return result;
}

1 Ответ

3 голосов
/ 09 мая 2020
template<typename ... T>
auto sum(T ... t)
{
   //getting the common type of the args in t and initialize a new var
   //called result using default constructor
   typename std::common_type<T...>::type result{};

  //(result += t, 0) ... this just sum the result and the next arg in the
  //parameter pack and then returns zero, hence the initializer_list will be filled 
  //only by zeros and at the end result will hold the sum of the args 
   std::initializer_list<int>{ (result += t, 0) ... };

   return result;
}

Это эквивалент

template<typename ... T>
auto sum(T ... t)
{
    return (t+...);
}
...