1

Imagine we have a variadic function void foo(T args...) for an existing type T.

In Java (void foo(T... args)) and C# (void foo(params T[] args)) passing an array of type T T[] is a valid way to pass it's contents as arguments to foo.

In Scala (def foo(args: T*): Unit) I may pass a Seq[T].

How do I pass the contents of a container (array, vector, iterator, whatever) as arguments to a variadic function in C++? Is it even possible?

Dracam
  • 149
  • 2
  • 11
  • 1
    Looks like your question is a duplicate of [this](https://stackoverflow.com/questions/34929856/unpack-an-array-to-call-a-function-with-variadic-template) and [this](https://stackoverflow.com/questions/11044504/any-solution-to-unpack-a-vector-to-function-arguments-in-c) – NathanOliver Aug 07 '18 at 14:28
  • 1
    observe that `void foo (T args...)` is the same as `void foo (T args, ...)` (the comma before the ellipsis is optional) that is a C-style variadic function (so `va_list`, `va_start`, `va_arg`, `va_end`), not a C++11-style template variadic function; if you want a C++11-style variadic function, you have to write `template void foo (Ts ... args)` that define a variadic function that receive a variadic list of (potentially) different types. If you want a variadic list of element of the same type... well, is a little complicated. – max66 Aug 07 '18 at 19:04
  • @NathanOliver Both questions are related, but I don't think they quallify as duplicates, since each question tackles a specific situation whereas this question deals with the more general idea of whether a varargs call with a container is possible this way. I have been googling for a few days now but couldn't find an answer so here we are. Chances are that other C++ beginners won't find the linked questions either. – Dracam Aug 07 '18 at 19:06

1 Answers1

2

The varargs argument list in C++ is established at compile time, not at runtime, so if anything, you can only pass a fixed-length array of items in.

You can call a function with a tuple of arguments using std::apply(). You can create a tuple from a fixed size array.

Alternatively, you could also create your own apply-like template helper function which recursively assembles a parameter pack from the elements of an array and calls the function for you, or use one of the myriad of metaprogramming helpers from the standard library to do it for you.

pmdj
  • 22,018
  • 3
  • 52
  • 103