I want to accept some inputs for a program,the inputs are integer values. The condition on accepting the inputs is number of inputs is not fixed but maximum number of inputs to be taken is fixed. for example lets say the maximum input limit is 15 inputs. So I should be able to accept "n" inputs where "n" can have any value from 1 to 15. Is there a way to do this in cpp?
Asked
Active
Viewed 244 times
0
-
This link may be relevant http://stackoverflow.com/questions/1657883/variable-number-of-arguments-in-c – rhodysurf Nov 21 '14 at 17:03
-
Are you looking for a variable number of arguments to the console application? Or a variable number of arguments to a function call. Both can be done. – sfjac Nov 21 '14 at 17:06
-
@sfjac variable number of arguments to a function call – Anuj Nov 21 '14 at 17:08
-
It seems that you just want: `void DoSomeStuff(int &array[15]);` – Quest Nov 21 '14 at 17:11
1 Answers
0
There is a general mechanism in C and C++ for writing functions that accept an arbitrary number of arguments. Variable number of arguments in C++?. However, this will not create a restriction on the number of args or restrict the overloads to a fixed type and it is generally a bit clunky to use (IMO).
It is possible to do something with variadic templates, for instance:
#include <iostream>
#include <vector>
using namespace std;
void vfoo(const std::vector<int> &ints)
{
// Do something with the ints...
for (auto i : ints) cout << i << " ";
cout << endl;
}
template <typename...Ints>
void foo(Ints...args)
{
constexpr size_t sz = sizeof...(args);
static_assert(sz <= 15, "foo(ints...) only support up to 15 arguments"); // This is the only limit on the number of args.
vector<int> v = {args...};
vfoo(v);
}
int main() {
foo(1);
foo(1, 2, 99);
foo(1, 4, 99, 2, 5, -33, 0, 4, 23, 3, 44, 999, -43, 44, 3);
// foo(1, 4, 99, 2, 5, -33, 0, 4, 23, 3, 44, 999, -43, 44, 3, 0); // This will not compile
// You can also call the non-template version with a parameter pack directly:
vfoo({4, 3, 9});
// Downside is that errors will not be great; i.e. .this
// foo(1.0, 3, 99);
// /Users/jcrotinger/Work/CLionProjects/so_variadic_int_function/main.cpp:21:22: error: type 'double' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing]
// vector<int> v = {args...};
// ^~~~
// /Users/jcrotinger/Work/CLionProjects/so_variadic_int_function/main.cpp:38:5: note: in instantiation of function template specialization 'foo<double, int, int>' requested here
// foo(1.0, 3, 99);
// ^
return 0;
}
The static assert is the only thing that will limit this to 15 arguments. As the comment indicates, type checking is messy since the error message will come not from the function call but from the initialization of the vector.
This does require support for C++ 11's variadic templates.