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)
Define a conversion operator:
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.