Question:
Is this notation possible in C++? add(1)(2);
I met this expression in codvars tasks, the task is that with such a record, the function must sum up all the arguments passed to it, i.e. in the case of such a record add(1)(2);
the answer should be 3 if the entry is add(1)(2)(3);
then, respectively, 6. As far as I know, there is no such way of passing arguments to a function in c++.
Answer:
You can make a simple class:
#include <iostream>
using std::cout;
using std::endl;
class add
{
public:
add(int val): sum(val) {}
add& operator()(int val)
{
sum += val;
return *this;
}
operator int() const
{
return sum;
}
private:
int sum;
};
int main()
{
cout << add(1) << endl;
cout << add(1)(2) << endl;
cout << 5 + add(0)(1)(2)(3)(4)(5) << endl;
return 0;
}
1
3
20