如何在VC ++ 6.0中模拟可变参数宏? [英] How to mimic variadic macro in VC++6.0?
问题描述
在 VS2010 中,我编写了以下可变参数宏以将信息转储到文件中.
In VS2010, I wrote the following variadic macros to dump out information to files.
#define INDENT(fp, indent) for(size_t __i = 0; __i < (indent); ++__i) fprintf((fp), " ")
// IND_FP = indented fprintf.
// This macro uses two IMPLICIT parameters.
// 1. (FILE *)fp is a pointer to the output file.
// 2. (size_t)indent specifies the indentation level.
#define IND_FP(format, ...) do{ INDENT(fp, indent); fprintf(fp, format, __VA_ARGS__); }while(0)
这些宏经常出现在我的程序中.
These macros frequently occur in my program.
void CMAP::dump_info(FILE *fp, size_t indent){
IND_FP("<cmap tableVersion=\"0x%08x\" numberOfEncodingTables=\"%d\">\n",
table_version_number, num_encoding_tables);
//...
IND_FP("</cmap>\n");
}
遗憾的是,现在我必须将代码迁移到以前的IDE( VC ++ 6.0 ),后者不不支持可变宏.我写了一个可变参数函数.
Sadly, now I have to migrate my code to the antediluvian IDE, VC++6.0, which does NOT support variadic macro. I wrote a variadic function instead.
void IND_FP(FILE *fp, size_t indent, char *format, ...){
INDENT(fp, indent);
va_list arg_ptr;
va_start(arg_ptr, format);
vfprintf(fp, format, arg_ptr);
va_end(arg_ptr);
}
但是我必须将数十行代码(如果不是几百行)从IND_FP(format, ...)
更改为IND_FP(fp, indent, format, ...)
.
But I have to change the tens if not hundreds lines of code from IND_FP(format, ...)
to IND_FP(fp, indent, format, ...)
.
是否有任何宏技巧可以帮助我?还是我最好使用显式参数并习惯冗余?
Is there any trick of macro that can help me out? Or I'd better use explicit arguments and get used to redundancy?
推荐答案
您可以通过不使用它们来获得圆形等角函数.使用ofstream代替FILE *.像这样
You could get round variadics by not using them. Use ofstream instead of FILE*. Something like this
#define LOGGER(logfile,loginfo) logfile << loginfo << std::endl
假设您已声明一个名为logfile的流.对于简单的事情,您可以使用
Say you've declared an ofstream called logfile. For simple things, you can use
LOGGER(logfile, x);
如果您想变得更复杂,可以使用
If you wish to get more complex, you could use
LOGGER(logfile, "x = " << x << " b=" << b);
对于缩进,您可以使用全局
For the indent, you could use a global
// declaration
char spaces[128];
...
// Initialization
memset(spaces, ' ', sizeof(spaces));
#define LOGGER(logfile,indent,loginfo) \
spaces[indent] = '\0'; \
logfile << spaces << loginfo << std::endl; \
spaces[indent] = ' '
以同样的方式,如果您希望缩进3
So in the same way, if you wish to indent by 3
LOGGER(logfile, 3, "x=" << x << " y=" << y << " z=" << z);
C ++<<在格式化方面不如printf优雅,但可以解决使用variadics的问题.
C++ << is not as elegant as printf for formatting but it will get you round the problem of using variadics.
这篇关于如何在VC ++ 6.0中模拟可变参数宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!