用户定义的C++转换为字符串(如Python中的__repr__)

Sla*_*a V 8 c++ casting

如何__repr__在Python中创建类似用户定义的内容?

比方说,我有一个object1SomeClass,比方说我有一个函数void function1(std::string).有没有办法定义一些东西(函数,方法,...)来使编译器转换类SomeClass来std::string调用function1(object1)

(我知道我可以使用stringstream缓冲区和operator <<,但我想找到一种没有中间操作的方法)

Pav*_*aev 14

定义转换运算符:

class SomeClass {
public:
    operator std::string () const {
        return "SomeClassStringRepresentation";
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,这不仅适用于函数调用,而且在任何上下文中编译器都会尝试将类型与std::string初始化和赋值,运算符等匹配.所以要小心,因为编写代码太容易了许多隐式转换难以阅读.


sha*_*oth 7

使用转换运算符.像这样:

class SomeClass {
public:
    operator string() const { //implement code that will produce an instance of string and return it here}
};
Run Code Online (Sandbox Code Playgroud)