Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard way to convert a class to a string

Tags:

c++

c++11

In Java, the standard is to define the method toString() to return a string representation of a class. Other than overloading operator<<, is there any such standard in C++? I know there are the std::to_string() methods to get a string representation of a number. Does the C++ standard speak of defining the method to_string() to serve similar purpose for a class, or is there a common practice followed by C++ programmers?

like image 717
Ahmed A Avatar asked Oct 26 '15 23:10

Ahmed A


People also ask

How do you turn a class into a string?

toString() converts the object to a string. The string representation is the string "class" or "interface", followed by a space, and then by the fully qualified name of the class in the format returned by getName.

How do you convert a string object to a class object?

We can also convert the string to an object using the Class. forName() method. Parameter: This method accepts the parameter className which is the Class for which its instance is required. Return Value: This method returns the instance of this Class with the specified class name.


1 Answers

The standard way to do this kind of thing is to provide an insertion operator so that an object can be inserted into a stream -- which may be any kind of stream, such as a stringstream.

If you wish, you can also provide a method that converts to a string (useful for your insertion operator), and, if you find the conversion acceptable, you can provide a 'to string' operator.

Here's my standard 'point' class example:

template <typename T>
struct point
{
  T x;
  T y;
  point(): x(), y() { }
  point( T x, T y ): x(x), y(y) { }
};

template <typename T>
std::ostream& operator << ( std::ostream& outs, const point <T> & p )
{
  return outs << "(" << p.x << "," << p.y << ")";
}

I also tend to keep a handy function around to convert things to strings:

template <typename T>
std::string to_string( const T& value )
{
  std::ostringstream ss;
  ss << value;
  return ss.str();
}

Now I can use it easily:

int main()
{
  point p (2,-7);

  std::cout << "I have a point at " << p << ".\n";

  my_fn_which_takes_a_string( to_string(p) );

You'll find that the Boost Lexical Cast Library is also designed for this kind of thing.

Hope this helps.

like image 200
Dúthomhas Avatar answered Oct 23 '22 19:10

Dúthomhas