In Lisp, we can use variadic function parameters like this:
(in Emacs shell)
~ $ (+ 1 2 3)
6
~ $ (+ 3 4.5 1)
8.5
~ $
In C++, we don't have such abilities.
C++ 11 introduced variadic templates, which can simulate this in compile time.
code:
#include <iostream>
template <typename T>
auto Add(T n) {
return n;
}
template <typename T, typename... Args>
auto Add(T n1, Args... args) {
return n1 + Add(args...);
}
int main() {
std::cout << Add(3, 1.1, 4, 9, 1) << std::endl;
return 0;
}
The disadvantage is, we can't use this feature in runtime, e.g., read some numbers, then call Add. The only way is use std::accumulate , but this is not feasible in all circumstance.