jmasterx
jmasterx

Reputation: 54143

Making my own printf function?

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?

Upvotes: 2

Views: 1568

Answers (1)

James McNellis
James McNellis

Reputation: 355207

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.

Upvotes: 10

Related Questions