[可变标准模板函数中的std :: initializer_list用法

问题描述 投票:0回答:1

我不明白下面的代码片段是如何工作的。特别是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;
}
c++ c++11 c++14 variadic-templates
1个回答
3
投票
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.