Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-defined cast to string in C++ (like __repr__ in Python)

Tags:

c++

casting

How do I make something like user-defined __repr__ in Python?

Let's say I have an object1 of SomeClass, let's say I have a function void function1(std::string). Is there a way to define something (function, method, ...) to make compiler cast class SomeClass to std::string upon call of function1(object1)?

(I know that I can use stringstream buffer and operator <<, but I'd like to find a way without an intermediary operation like that)

like image 792
Slava V Avatar asked Jul 15 '09 06:07

Slava V


People also ask

What is __ repr __ method in Python?

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

What is str and repr in Python?

Both str() and repr() return a “textual representation” of a Python object. The difference is: str() gives a user-friendly representation. repr() gives a developer-friendly representation.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

__str__ is used in to show a string representation of your object to be read easily by others. __repr__ is used to show a string representation of the object.

Is str a class in Python?

Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used.


1 Answers

Define a conversion operator:

class SomeClass {
public:
    operator std::string () const {
        return "SomeClassStringRepresentation";
    }
};

Note that this will work not only in function calls, but in any context the compiler would try to match the type with std::string - in initializations and assignments, operators, etc. So be careful with that, as it is all too easy to make the code hard to read with many implicit conversions.

like image 151
Pavel Minaev Avatar answered Oct 25 '22 15:10

Pavel Minaev