How To Pass A Paramter List In C++

Started by
7 comments, last by MaulingMonkey 15 years, 11 months ago
I would like to create a function that can pass a parameter list to another function in C++. I tried the following.

void MyFunc(const char *fmt, ...) 
{
    va_list ap;
    va_start(ap,fmt);
    printf(fmt, ap); //should just print out what I pass it
    va_end(ap);
}
This compiles just fine. I tested with this.

int num =5;
MyFunc("Num is %d\n", num);
I get "Num is 1235752" What is it giving me back? Obviously, my code is wrong. Is there a way to do this correctly? Thanks in advance.
Advertisement
Hi,

The second parameter in your printf call is wrong. You are using ap, which is of type va_list, which is only used to hold parameter retrieval state and is to be only used as a parameter to va_start, va_arg and va_end calls.

To retrieve the next parameter you have to use va_arg. So that line should correctly read:

printf(fmt, va_arg(ap,int));


Refer to the documentation for additional details - for example here
I'm pretty convinced that this is only possible by using macros.

Morrandirs suggestion doesn't work if you pass more than one argument, obviously.
| Stein Nygård - http://steinware.dk |
Sorry, I guess it wasn't really a "suggestion". Just the correct version of that specific line.
| Stein Nygård - http://steinware.dk |
Yes, I should have been more clear, what I posted wasn't really a solution to the whole problem, just the correct way to use the va_list family of macros.
You need to call vprintf rather than printf so the code should be:

void MyFunc(const char *fmt, ...)
{
va_list ap;
va_start(ap,fmt);
vprintf(fmt, ap); //should just print out what I pass it
va_end(ap);
}
Thanks for all the help. I'll give it a try. Thanks again.
Quote:Original post by fathom88
I would like to create a function that can pass a parameter list to another function in C++.


In C++, don't do this. We have a real type system now. It wants to help you avoid making errors that crash your program without telling you anything useful. This kind of offer is hard to refuse.

// Equally as useless as the OP's example ;)#include <iostream>struct MyOutputter {} MyFunc;template <typename T>MyOutputter& operator<<(MyOutputter& out, const T& t) {  std::cout << t;  return out;}
Quote:Original post by Zahlman
...


This is known as operator chaining. For printf-like applications, look into boost::format, which brings the advantages of type safety, object safety, and defined behavior to the table. (boost::format accomplishes this by using operator chaining)

This topic is closed to new replies.

Advertisement