简体   繁体   English

制作我自己的printf功能?

[英]Making my own printf function?

I was wondering how I could do this. 我想知道我怎么能做到这一点。 I'm mostly puzzled by the N arguments part: 我对N个论点部分感到困惑:

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. 我想创建一个函数,它将采用这样的格式化字符串并返回一个std字符串。

How is the N arguments part done? N个参数部分是如何完成的?

printf is a variadic function; printf是一个可变函数; you can implement your own variadic functions using the facilities provided by <stdarg.h> . 您可以使用<stdarg.h>提供的工具实现自己的可变参数函数。

In C++, you should avoid variadic functions wherever possible. 在C ++中,应尽可能避免使用可变参数函数。 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++; C ++ 0x为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. 例如, Boost.Format重载%运算符以执行格式化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM