Seneca the Younger.
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:
1 2 3 4 5 |
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
Another example:
1 2 3 4 5 |
template<typename... Ts> inline void trace(Ts&&... args) { (cout << ... << args) << endl; } |
Here in line
Another way of doing the same is:
1 2 3 4 5 |
template<typename... Ts> inline void trace(Ts&&... args) { ((cout << args << " "),...) << endl; } |
Here the
That’s it for now 🙂 I’ll post more as I learn more!
Complete listing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#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; } |