Search code examples
c++c++11templatesc++14variadic-templates

std::initializer_list usage in variadic template function


I can't understand how below code snippet works. Especially std::initializer_list usage.

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

   return result;
}

Solution

  • 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;
    }
    

    It's equivalent to

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