CPP
cpp
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
26
27
//How to have function with variable number of argument? Type of argument is same and it's fix that it is for int. So, variadic template is not a good choice as we have to block all other data type. Dont want to use variadic function.
//Below three options are there:
//1. Initializer_list... Works on rvalue as well as lvalue. Refer function add
//2. more methods, we have it on below discussion thread:
//https://www.sololearn.com/Discuss/2350838/variadic-template-is-only-option
#include <iostream>
#include <initializer_list>
using namespace std;
auto add(initializer_list<int> il)
{
int sum = 0;
for(const auto& a:il)
sum += a;
return sum;
}
int main()
{
int a = 9, b = 7, c = 8,d=1;
cout << "5+3+2 = " << add({5,3,2}) << endl;
cout << "9+7+8+1 = " <<add({a,b,c,d}) << endl;
return 0;
}
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run