in c++,is there something similar to the "arguments" object in javascript?

hello guys...
maybe some of you had a previous experience with javascript.
in javascript,there's something called the "arguments" object,this object is basically used to access the parameters of a function,for example,instead of writing:
1
2
3
function sum(x,y) {
    return x+y;
}

you might write:
1
2
3
function sum() {
    return arguments[0]+arguments[1];
}

my real question is:
how can i perform the same task in c++?
Last edited on
No.

In C++ the number of function arguments and their types are fixed at compile time. You can have multiple functions with the same name as long as the function arguments differ. The compiler will then choose which one to call based on the type of the arguments that you pass to the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int sum(int x, int y)
{
	return x + y;
}

double sum(double x, double y)
{
	return x + y;
}

int main()
{
	std::cout << sum(100, 102) << '\n'; // this will call sum(int,int)
	std::cout << sum(1.3, 2.2) << '\n'; // this will call sum(double,double)
}


I'm not sure what it is you're trying to accomplish, but if you want to write a sum function that works for any type and/or for any number of arguments you can do that using templates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

// This function template allows you to calculate the sum of any type.
template <class T>
T sum(T x, T y)
{
	return x + y;
}

// This variadic function template allows you to calculate the sum of any number of arguments.
template <class T, class ...Args>
T sum(T x, Args... args)
{
	return x + sum(args...);
}

int main()
{
	std::cout << sum(1, 2, 3, 4, 5, 6) << '\n';
	std::cout << sum(1.3, 2.2, 22.001) << '\n';
}
Last edited on
How can i perform the same task in c++?

The solution is possible with a code generator, but nothing else is sufficient. A rudimentary solution may be possible with the C preprocessor only, but I would need to look into that.

This seems like an XY Problem:
http://xyproblem.info/

Why do you want to do this?
I suspect there's a much superior way to get achieve your actual goal that probably involves templates.
Last edited on
Topic archived. No new replies allowed.