为什么字符串类没有预定义的<< operator(operator <<),以便字符串像ostringstreams一样工作?(Why doesn't the string class have a << operator (operator<<) predefined so that strings work like ostringstreams?)

在我看来,定义<< operator(operator <<)直接使用字符串比使用ostringstreams然后转换回字符串更优雅。 有没有理由说c ++不能开箱即用?

#include <string> #include <sstream> #include <iostream> using namespace std; template <class T> string& operator<<(string& s, T a) { ostringstream ss; ss << a; s.append(ss.str()); return s; } int main() { string s; // this prints out: "inserting text and a number(1)" cout << (s << "inserting text and a number (" << 1 << ")\n"); // normal way ostringstream os; os << "inserting text and a number(" << 1 << ")\n"; cout << os.str(); }

It seems to me that defining the << operator (operator<<) to work directly with strings is more elegant than having to work with ostringstreams and then converting back to strings. Is there a reason why c++ doesn't do this out of the box?

#include <string> #include <sstream> #include <iostream> using namespace std; template <class T> string& operator<<(string& s, T a) { ostringstream ss; ss << a; s.append(ss.str()); return s; } int main() { string s; // this prints out: "inserting text and a number(1)" cout << (s << "inserting text and a number (" << 1 << ")\n"); // normal way ostringstream os; os << "inserting text and a number(" << 1 << ")\n"; cout << os.str(); }

更多推荐