Click here to Skip to main content
14,036,655 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

1.2K views
Posted 15 Mar 2019
Licenced CPOL

Short Introduction to Parameter Packs and Fold Expressions

, 15 Mar 2019
Rate this:
Please Sign up or sign in to vote.
Short introduction to parameter packs and fold expressions

I’m new to this topic since I literally just learned about the fold expressions today, and parameter packs days before that, so it will be a short post where I’ll explain the basics.

Let’s jump straight to the code:

template<typename... Args>
int sum(Args&&... args)
{
    return (args + ...);
}
  • Line 1 tells us there will be zero or more parameters.
  • Line 2 declares a function with said variable number of parameters.
  • Line 4 is where the magic happens. The fold expression states that for every parameter in the args parameter pack, combine it with the next one using operator+. So it becomes args0 + args1 + ... + argsN.

Another example:

template<typename... Ts>
inline void trace(Ts&&... args)
{
    (cout << ... << args) << endl;
}

Here in line 4, the fold expression takes the form of “(init op … op pack)” as described by syntax #4 here. It expands to cout << args0 << args1 << ... << argsN.

Another way of doing the same is:

template<typename... Ts>
inline void trace(Ts&&... args)
{
    ((cout << args << " "),...) << endl;
}

Here, the cout << args << " " is expanded N times, separated by the comma operator, so it’s less efficient but we get a space between each printed argument.

That’s it for now. 🙂 I’ll post more as I learn more!

Complete Listing

#include <iostream>
using namespace std;
 
template<typename... Args>
int sum(Args&&... args)
{
    return (args + ...);
}
 
template<typename... Ts>
inline void trace(Ts&&... args)
{
    //(cout << ... << args) << endl;
    ((cout << args << " "),...) << endl;
}
 
int main(int argc, char** argv)
{
    trace(sum(1));
    trace(sum(1,2,3,4,5));
    trace(sum(1,1,2,3,5,8,13,21,34,55));
    trace(1, 2, 3);
 
    return 1;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Martin Vorbrodt
Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190424.1 | Last Updated 15 Mar 2019
Article Copyright 2019 by Martin Vorbrodt
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid