Slava V
Slava V

Reputation: 17256

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

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)

Upvotes: 10

Views: 6567

Answers (2)

Pavel Minaev
Pavel Minaev

Reputation: 101595

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.

Upvotes: 15

sharptooth
sharptooth

Reputation: 170489

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}
};

Upvotes: 7

Related Questions