0

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

1 Answer 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;
}

It's equivalent to

template<typename ... T>
auto sum(T ... t)
{
    return (t+...);
}
Sign up to request clarification or add additional context in comments.

6 Comments

It makes me sad that we need hackery like this in C++ to quickly navigate parameter packs. How is this expressive?!
How can initializer_list perform recursively inside parenthesis ?
@MustafaCOKER It doesn't. this (result += t, 0) ... returns 0,0,0,.. inside the parenthesis. like if you write {0,0,0,...}
Hi Guys, Sorry but I cant understand the role of zero after result += t. And also, compiler doesnt care this parameter. If I changed it(result += t, 2 or result += t, false), result remains same. And If I delete this param, result remains same again, but compiler gives warning.
I got it. Thank you very very very much.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.