June 2025
Intermediate to advanced
1093 pages
33h 24m
English
The add function discussed previously can take up to five arguments, and it would certainly not be difficult for you to extend this to 20 or even 100 default arguments. I don't want to leave the example as is without giving you a glimpse that you can handle an arbitrary number of arguments. If you want an add function that takes an arbitrary number of int values, take a detour via std::initializer_list:
int add(std::initializer_list<int> ns) { return std::accumulate(begin(ns), end(ns), 0); // or a for loop}
Now, when calling, you just need to add a few curly brackets around the arguments, but they can be any number. For example:
add({1,2,3,4,5,6,7,8,9})
Read now
Unlock full access