开发者

C++: Is it possible to get a std::string out of an object that overloads the << operator?

I have an object that can be printed to the console with std::cout << obj, but I can't get a std::string out of it, because it doesn't seem to implement something like a .string() method. I thought I might be able to use that overloaded operator to just get string representations of everything instead of havin开发者_如何学运维g to implement a function to do it myself every time I need it, though having found nothing on the subject makes me think this isn't possible.


Use a std::ostringstream. It is a C++ stream implementation which writes to a string.


You can use a std::ostringstream.

std::ostringstream os;
os << obj;
std::string result = os.str();


There are different ways of doing it, you can manually implement it in terms of std::ostringstream, or you can use a prepacked version of it in boost::lexical_cast. For more complex operations, you can implement a in-place string builder like the one I provided as an answer here (this solves a more complex problem of building generic strings, but if you want to check it is a simple generic solution).


It seems that the linked question has been removed from StackOverflow, so I will provide the basic skeleton. The first think is to consider what we want to use with the in-place string builder, which basically is avoiding the need to use create unnecessary objects:

void f( std::string const & x );
f( make_string() << "Hello " << name << ", your are " << age << " years old." );

For that to work, make_string() must provide an object that is able to take advantage of the already existing operator<< for the different types. And the whole expression must be convertible to std::string. The basic implementation is rather simple:

class make_string {
   std::ostringstream buffer;
public:
   template <typename T>
   make_string& operator<<( T const & obj ) {
      buffer << obj;
      return *this;
   }
   operator std::string() const {
      return buffer.str();
   }
};

This takes care of most of the implementation with the very least amount of code. It has some shortcomings, for example it does not take manipulators (make_string() << std::hex << 30), for that you have to provide extra overloads that take the manipulators (function pointers). There are other small issues with this implementation, most of which can be overcome by adding extra overloads, but the basic implementation above is enough for most regular cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜