2

I was wondering how I could do this. I'm mostly puzzled by the N arguments part:

printf("Hello, I'm %i years old and my mom is %i .",me.age(),mom.age());

I want to make a function that will take a formatted string like this and return a std string.

How is the N arguments part done?

1 Answer 1

10

printf is a variadic function; you can implement your own variadic functions using the facilities provided by <stdarg.h>.

In C++, you should avoid variadic functions wherever possible. They are quite limited in what types they can accept as arguments and they are not type safe. C++0x adds variadic templates to C++; once support for this feature is widespread, you'll be able to write type safe variadic functions.

In the meantime, it's best to use some other type safe method. Boost.Format, for example, overloads the % operator to perform formatting.

Sign up to request clarification or add additional context in comments.

10 Comments

@James McNellis: Why are variadic limited ? I think the only limitation is the stacksize. You can use any type as long as it's interpreted right.
@Edwin, they are limited in that you cannot pass in a user-defined structure. (E.g. passing an std::string).
@Edwin: Among other things, all arguments passed in the variable arguments pack must be POD.
@Michael: You can pass a class-type object as long as it is POD.
@Micheal: ... and you can always pass a pointer to any type or array.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.