這可以使用自定義的流操縱器來完成,該流操縱器將所需的縮進級別存儲在流的內部可擴展數組的字中。您可以使用功能ios_base::xalloc
來請求這樣一個詞。這個功能會給你你單詞的索引。您可以使用ios_base::iword
訪問它。一種方式來實現,這將是這樣的:
struct indent {
indent(int level) : level(level) {}
private:
friend std::ostream& operator<<(std::ostream& stream, const indent& val);
int level;
};
std::ostream& operator<<(std::ostream& stream, const indent& val) {
for(int i = 0; i < val.level; i++) {
stream << " ";
}
return stream;
}
std::ostream& operator<<(std::ostream & oStream, const OwnClass& iOwnClass) {
oStream << indent(oStream.iword(index)) << "[SomeMember1: " <<
iOwnClass._ownMember1 << "]\n";
oStream << indent(oStream.iword(index)) << "[SomeMember2: " <<
iOwnClass._ownMember2 << "]\n";
}
你必須弄清楚在哪裏存儲index
。這實際上允許您將自定義狀態添加到流中(請注意,這不會是線程安全的開箱即用)。每個想要縮進的函數都應該將請求的縮進添加到流中,並在完成時再次減去它。你可以確保這始終使用保護加/減所需的縮進(恕我直言,這是比使用機械手更優雅)發生:
class indent_guard {
public:
indent_guard(int level, std::ostream& stream, int index)
: level(level),
stream(stream),
index(index)
{
stream.iword(index) += level;
}
~indent_guard() {
stream.iword(index) -= level;
}
private:
int level;
std::ostream& stream;
int index;
};
你可以使用這樣的:
void some_func() {
indent_guard(2, std::cout, index);
// all output inside this function will be indented by 2 spaces
some_func(); // recursive call - output will be indented by 4 spaces
// here it will be 2 spaces again
}
工作完美!我做了一些更改,例如添加increaseIndent和decreaseIndent方法。我的日誌現在看起來完全是我想要的。謝謝。 – 2012-03-07 14:04:25
@James:請問你有更復雜的代碼嗎? – Cookie 2014-06-05 08:32:41