Custom string casting in C ++ (e.g. __repr__ in Python)

How to do something like custom __repr__ in Python?

Let's say I have 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 the SomeClass compiler class to std::string after calling function1(object1) ?

(I know that I can use the string buffer and the <<operator, but I would like to find a way without an intermediate operation)

+4
source share
2 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 will try to match the type with std::string - with initialization and assignments, operators, etc. Therefore, be careful with this, as it is all too easy to make the code difficult to read with many implicit conversions.

+11
source

Use the conversion operator. Like this:

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

All Articles