Sign in to follow this  
NamelessTwo

C++ and var_list

Recommended Posts

Guest Anonymous Poster   
Guest Anonymous Poster
Quote:
Original post by NamelessTwo
Is there a C++ alternative to these?
va_arg
va_end
va_start


Try this.

#include

using namespace std;

Quote:
How to implement a function in C++ with unknown number or parameters?


You can't pass objects through the ellipsis. You can pass pointers to objects.

By using the ellipsis, you forfeit the string type checking and compile-time safety available through C++.

Notice how in the C++ standard library the use of varargs functions is replaced by chaining operators (eg. cout vs. printf).

Share this post


Link to post
Share on other sites
demonkoryu    980
See boost::format for an example where C++ operator chaining improved on the vast shortcomings of the printf-style ellipsis construct.

Can't resist to quote Zahlman's signature:
"Basically whenever you invoke the dread ellipses construct you leave the happy world of type safety." -- SiCrane

Share this post


Link to post
Share on other sites
Prototype    2014
Here's a little example of how you can overload the << operator to perform chaining. Note that the result of the operation is a reference to the object itself.


struct _func {
_func& operator <<(const int i) { /* do stuff with int */; return *this; }
_func& operator <<(const double f) { /* do stuff with double */ return *this; }
_func& operator <<(const std::string& s) { /* do stuff with string */; return *this; }
} func;


func << 42 << "Hello" << "world" << 3.14;


Share this post


Link to post
Share on other sites
swiftcoder    18432
Quote:
Original post by Konfusius
See boost::format for an example where C++ operator chaining improved on the vast shortcomings of the printf-style ellipsis construct.


However, even boost::format's developers note that it is considerably slower than printf. I guess I mention this just to bring notice to the fact that the 'best' way of doing something is not always the most suitable for a given situation, although I agree that the elipses should be avoided whenever possible.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this