-1

Consider the following code:

#include <iostream>

int var_arg_func(...)
{
    std::cout << "Func called!";
}

int main()
{
    var_arg_func(0, 1, 2);
}

As you can see here I can pass a variable number of arguments to the function var_arg_func.

But my question is how can I access those arguments from the function itself? (I'm using C++20)

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
The Coding Fox
  • 1,488
  • 1
  • 4
  • 18

1 Answers1

2

You can use variadic templates. One example for printing out all the passed argument is given below:

#include <iostream>
//provide an ordinary function to end recursion
void print ()
{
}

template<typename T, typename... Types>
void print (T firstArg, Types... args)
{
    std::cout << firstArg << "\n"; // printing the very first argument passed 
    print(args...); // printing the rest of the argument by calling print()
}

int main()
{
    print(1, 2, 3, "some string literal");//call function template print() with arguments `1`, `2`, `3` and `"some string literal"`
    return 0;
}

In the above snippet, if we call print() with one or more arguments then the templated version of print will be used/called which just prints the very first argument passed(which is 1 in my example) using cout and then calls print with the remaining arguments(which are 2, 3 and "some string literal.

Now the whole process repeats. In particular, the very first argument 2 is printed using cout and then print is called with the remaining arguments(3, "some string literal").

This goes on until there are no more arguments to pass and in this case when print is called with no arguments then the ordinary non-template function print will be used/chosen, thus ending the recursion.

The output of the above program can be seen here:

1
2
3
some string literal

Note that there are other ways as well like using fold expression(with C++17) to do the same. Also, in the above example, the arguments are passed by value. You can modify the program to pass them by reference according to your needs.

With C++17, you can use fold expression:

#include <iostream>
template<class... Args>
void print(const Args&... args)
{
    (std::cout << ... << args) << "\n"; //uses fold expression
}

int main()
{
    print(1, 2, 3, "some string literal");
    return 0;
}
Jason
  • 36,170
  • 5
  • 26
  • 60
  • side note: The output of the second way is different. – IkarusDeveloper Feb 22 '22 at 15:32
  • Yes i am aware, the output of the second is `123some string literal`. It can be formatted according to the needs of the user by adding a `Helper` class. Since, there is no such constraint in OP's original question, i didn't bother to do so. I wanted to just show/print the arguments without formatting them. – Jason Feb 22 '22 at 15:38