【发布时间】:2019-01-25 13:39:04
【问题描述】:
我尝试用 C++ 为 printf 编写一个包装器。当然,我找到了va_list,但不知道它如何适用于我,因为
包装器不会被直接调用。我稍后会展示。
我解析了一个脚本,其中包含一个带有未知数量参数的函数,例如
ASTNode node(Token(PRINT, PRINT));
consume(PRINT);
consume(LPAREN);
node.make_child(variable()); // <-- formatstring (node.child[int])
while(current_token._type() != RPAREN) {
consume(COMMA);
node.make_child(variable()); // <-- the values to replace in formatstring (node.child[int++])
i++;
}
consume(RPAREN);
return node;
第一个是格式字符串,其他是格式字符串中要替换的值,所以我执行它的函数看起来像
if(node._token()._type() == PRINT) {
Token formatstring = visit(*node.child[0]);
Token temp;
int i = 1;
while(i < node.child.size()) {
visit(*node.child[i++]); // <-- the values to replace in formatstring
}
}
并且不采用任何“真实”参数。如何使用 va_list 或其他方法构建动态参数数组?
谢谢
编辑似乎有人不清楚我的问题..
printf 被称为printf(formatstring, param1, param2, param3...),我想在循环中构建在第一个参数(格式字符串)之后传递的参数
// Pseudocode
out("printf(");
out($myformatstring);
int i = 1;
while(i<parameter_count) {
out(parameter[i++]);
out(",");
}
out(")");
【问题讨论】:
-
在我看来boost::format 更适合你。
-
@Jabberwocky 现在应该很清楚了。如果没有,没关系.. Nathan 我无法安装 boost
-
@bruno iostreams 令人厌恶,重载位移运算符是个坏主意。
标签: c++