开发者

C++ unlimited parameters to array

I have a function with following signature

char requestApiCall(int num, const wchar_t* pParams = 0, ...)
{
...
}

Now I want to to get all pParams in an array (or to be able to iterate over it). I know this is possible with some macros, but I have no idea how to do it.

Any help would be appreciated.

P.S. I'm using MinGW if it matters.

UPDATE


my question caused confusion. I will try to clarify (sorry for my grammar). Both Object Pascal and C# has the ability开发者_如何学编程 to pass unlimited amount of parameters to a method. In C# we achieve this with params keyword:

void Foo(params string[] strs)
{
...
}
Foo("first", "second", "another one", "etc");

I want to achieve same result in C++ without using any object/class. In my case, type safety is not a concern, but if there is a type safe way to achieve that goal, I will gladly hear your comments :)

Thanks


You need to look at the functions and macros declared in stdarg.h. Here is a tutorial that explains it.

http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html

I'm not sure what your function parameters are supposed to represent but I think you'll find that it needs to change.

By the way, I find that for C++ I can usually avoid variadic functions. This has the advantage of preserving type safety. Are you sure you really need a variadic function?


Using variadic function arguments is a dangerous and tricky business, and almost surely there is a better way - for example, you might pass an std::vector<std::wstring>& to your function!

OK, that said, here's how to use variadic arguments. The key point is that it is your responsibility to know the number and types of the arguments!

#include <cstdarg>

char requestApiCall(int num, const wchar_t* pParams, ...)
{
   va_list ap;             // the argument pointer
   va_start(ap, pParams);  // initialize it with the right-most named parameter

   /** Perform magic -- YOU have to know how many arguments you are getting! **/

   int a = va_arg(ap, int);      // extract one int
   double d = va_arg(ap, double) // one double
   char * s = va_arg(ap, char*)  // one char*
   /* ... and so forth ... */

   va_end(ap);             // all done, clean up
}

Just for completeness, I would redefine the function as this:

char requestApiCall(std::vector<std::wstring> & params)
{
  for (std::vector<std::wstring>::const_iterator it = params.begin(), end = params.end(); it != end; ++it)
  {
    // do something with *it
  }
  /* ... */
}


A good example of what you are trying to accomplish is the exec family of functions. exec() takes an variable list of arguments all of which are expected to be const char*. The last item is a NULL ((char*)0). The last item is the indicator for when the list of items is complete.

You can use the variadic macros in stdargs.h as others have described.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜