這是相當毛,並且僅適用於gcc
/g++
。
#define STRINGIFY_STR(x) \
std::string(({ std::ostringstream ss; \
ss << "[a: " << x.a \
<< ", f: " << x.f \
<< ", c: " << x.c << "]"; \
ss.str(); })).c_str()
您必須從值中創建字符串。請不要這樣做。請按照裏德的建議。
這是我會怎麼修改struct
允許它要美化打印:
struct Str
{
int a;
float f;
char *c;
std::ostream & dump (std::ostream &os) const {
return os << "[a: " << a
<< ", f: " << f
<< ", c: " << c << "]";
}
};
std::ostream & operator << (std::ostream &os, const Str &s) {
return s.dump(os);
}
Str s = {123, 456.789f, "AString"};
現在,打印出來s
,您可以使用std::cout
:
std::cout << s << std::endl;
或者,如果您真想要一個字符串:
std::stringstream ss;
s.dump(ss);
puts(ss.str().c_str());
來源
2012-06-16 01:16:20
jxh
stringify?宏?爲什麼不簡單地添加一個'toString'方法到你的對象或一個自由函數,它需要一個const引用來實現呢?如果性能不是問題,你甚至可以使用'std :: ostringstream'。 – AJG85
是否有一個特別的原因需要一個宏?爲Str類編寫'operator <<'會更好。 –