Variable number of parameters to a method

Hey everyone,

I'm having trouble writing code to pass a variable number of strings to a method. Everything compiles correctly, but it errors out:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "stdafx.h"
#include <string>
#include <cstdarg>
#include <iostream>

using std::string;
using namespace std;

void testMultipleArgs(int x, ...)
{
	va_list ap;
	va_start(ap, x);
	string tmp;

	for (int i = 0; i < x; i++)
	{
		tmp = va_arg(ap, string);
		cout << tmp << endl;
	}
	cout << "End" << endl;
	cin >> tmp;
}


int _tmain(int argc, _TCHAR* argv[])
{
	testMultipleArgs(3, "test1\n", "test2\n", "test3\n");
	return 0;
}


When I run this I get a "std::bad_alloc at memory location 0x0028f1a0."
It is not safe to use variadic argument lists with non-POD types. Use a standard container instead.

Give me a little bit and I'll see if I can give you something a little more satisfactory.
OK, here you go.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Example of homogeneous variable argument lists (by cheating).
//
// The syntax is not pretty, but we can co-opt C99 anonymous variadic macros
// to fix that. Keep in mind that this is still a pretty stupid way to use
// macros.

#include <iostream>
#include <string>
#include <vector>

// This thing collects the list of arguments
template <typename T, typename A = std::allocator <T> >
struct varargls: std::vector <T, A>
  {
  varargls( const T& v ):
    std::vector <T, A> ( 1, v )
    { }
  varargls& operator , ( const T& v )
    {
    push_back( v );
    return *this;
    }
  };

// This is our (rather ordinary) function
#define foo( x, ... ) FOO(( varargls <std::string> ( x ), __VA_ARGS__ ))
void FOO( varargls <std::string> args )
  {
  for (size_t n = 0; n < args.size(); n++)
    std::cout << n << ": " << args[ n ] << "\n";
  }

int main()
  {
  using namespace std;
  string foo = "Yeah!";  // Notice how the pre-processor is smart enough to
                         // distinguish between a variable and a function.
  foo( "Hello,", "world!", "", foo, "Good-bye." );
  return 0;
  }

I also recommend you to this article over at Stack Overflow
http://stackoverflow.com/questions/2396065/c-overloading-operator-comma-for-variadic-arguments

Enjoy!
Wow, thanks for that! I've only been programming in C++ for a week, so I'm having a litlte trouble following your code, but it looks like it'll do exactly what I want.

Thanks for taking the time to write it out.
Topic archived. No new replies allowed.