1

In modern C++(ie, version>=11), what is best way to implement a function with a variables number of int parameters?

I only want ints, not a general type.

Each of the parameters is of type int and no other type is allowed.

void foo(/*WHAT'S HERE*/) {
// and how do I access the arguments here?
}

int main()
{
  foo(34,1);
  foo(9,2,66,1);
  // etc
  return 0;
}
RFS
  • 311
  • 3
  • 8
  • 2
    I added another question to the duplicate list that covers restricting arguments to int – M.M Nov 22 '19 at 01:38
  • 1
    Why not pass in a `vector`? – stark Nov 22 '19 at 01:38
  • Why wouldn't this work: https://ideone.com/TvLalR – Brandon Nov 22 '19 at 03:29
  • @M.M Many, many, ..., many thank yous. The following works in C++17 and is a thing of immense beauty. ```template typename std::enable_if<(std::is_same::value && ...), void>:: type foo(U... ints) { const int size = sizeof...(ints); int intarray[size] = {ints...}; }``` – RFS Nov 24 '19 at 16:32
  • @RFS beauty is in the eye of the beholder :) – M.M Nov 24 '19 at 20:06

1 Answers1

-1

The best thing to do is use a variadic function.

template<typename T, typename ... Args>
return_type Functionname(T arg1, ...)
{ }

For example, if you want to sum a variable number of arguments, use something like:

template<typename T, typename... Args>
T adder(T first, Args... args) {
  return first + adder(args...);
}

Hope this helps!

EDIT: This question might help, too.

Variable number of arguments in C++?

GokuMizuno
  • 493
  • 2
  • 5
  • 14
  • How do I do this for int's? I only want int's. – RFS Nov 22 '19 at 01:24
  • 1
    Your syntax for the function parameters in the first snippet is not doing what you expect it to. You are declaring a variadic template for a (C-style) variadic function. The `adder` example lacks a base case and since C++17 fold expressions are a much more readable way of forming that example. Replacing `typename` by `int` makes the parameters non-type template parameters and your last code block ill-formed, because `Args` are not types. – walnut Nov 22 '19 at 01:27
  • @RFS The variadic template accepts *any* types for *any* argument, so it works fine with `int` arguments. If your question is how to limit the variadic template to *only* accept `int` as argument, then you should clarify that in the question. – walnut Nov 22 '19 at 01:34
  • 2
    @GokuMizuno "Replace all typename with int" is not possible – M.M Nov 22 '19 at 01:37