我正在使用一个用C++实现的开源UNIX工具,我需要修改一些代码才能让它实现我想要的功能。我想做最小的改变,希望我的补丁能在上游被接受。可以在标准C++中实现并且不会创建更多外部依赖项的解决方案是首选。
这就是我的问题。我有一个C++类--让我们称它为"A“--它目前使用fprintf()将其高度格式化的数据结构打印到文件指针。在它的print函数中,它还递归地调用几个成员类的相同定义的print函数("B“是一个例子)。还有另一个类C,它的成员std::string "foo“需要设置为A的实例的print()结果。可以将它看作A的to_str()成员函数。
在伪代码中:
class A {
public:
...
void print(FILE* f);
B b;
...
};
...
void A::print(FILE *f)
{
std::string s = "stuff";
fprintf(f, "some %s", s);
b.print(f);
}
class C {
...
std::string foo;
bool set_foo(std::str);
...
}
...
A a = new A();
C c = new C();
...
// wish i knew how to write A's to_str()
c.set_foo(a.to_str());
值得一提的是,C是相当稳定的,但A和B(以及A的其余依赖项)处于不断变化的状态,因此需要的代码更改越少越好。还需要保留当前的打印(FILE* F)接口。我考虑了几种实现A::to_str()的方法,每种方法都有优缺点:
- I wouldn't have to rewrite any format strings
- print() could be reimplemented as: fprint(f, this.to\_str());
- But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string
中捕获a.print()的结果
- I would have to convert all of the format strings to << output format. There are hundreds of fprintf()s to convert :-{
- print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though [this guy says it may be possible](http://synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html)).
使用Boost的字符串format library的
- More external dependencies. Yuck.
- Format's syntax is different enough from printf() to be annoying:
printf(format_str,args) -> cout << boost::format(format_str) % arg1 % arg2 %等
使用Qt的QString::asprintf()的
- A different external dependency.
那么,我是否已经用尽了所有可能的选择?如果是这样,你认为哪一个是我最好的选择?如果不是,我忽略了什么?
谢谢。
https://stackoverflow.com/questions/69738
复制相似问题