views:

326

answers:

2

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)

+5  A: 

Use a conversion operator. Like this:

class SomeClass {
public:
    operator string() const { //implement code that will produce an instance of string and return it here}
};
sharptooth
+7  A: 

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.

Pavel Minaev
Be careful: While `__repr__` might be idiomatic Python, the above most definitely is not idiomatic C++ and will confuse the heck out of readers of the code if not used judiciously.
EDIT: Pavel's answer is of course completely correct, it's the mention of `__repr__` that sounded my warning siren :)