c++ - std::string 的转换运算符无法处理赋值

标签 c++ conversion-operator

我正在使用代理类型来推迟工作,直到将结果分配给一个变量,它通过在代理类型上使用转换运算符来工作。为 std::string 添加转换运算符重载时,它适用于从代理构建字符串,但无法编译赋值,并显示以下错误消息:

error: ambiguous overload for 'operator='

虽然这个问题与 operator T() not used in assignment 的问题类似,这里的解决方案不适用,因为我也在使用模板化转换运算符。

下面是片段:

#include <iostream>
#include <string>

struct Proxy
{
    template < typename T >
    operator T ()
    {
        T res;
        std::cerr << "Converting to T: " << typeid( T ).name() << "\n";
        return res;
    }

    operator std::string ()
    {
        std::string res;
        std::cerr << "Converting to string\n";
        return res;
    }
};


int main()
{
    struct Foo {};

    Proxy proxy;

    bool b = proxy; // Construct, works
    b = proxy;      // Assignment, works

    Foo f = proxy; // Construct, works
    f = proxy;     // Assignment, works

    std::string s = proxy; // Construct, works
    s = proxy;             // Assignment, this line fails to compile <<<<<

    return 0;
};

如何使这个代理与字符串赋值一起工作?

最佳答案

How can this proxy be made to work with the string assignment?

编译器无法判断您想要什么转换。它可以是任何可用于构造 std::string - charchar *std::string, ...

所以解决办法就是告诉编译器你想要什么。进行显式运算符(operator)调用:

s = proxy.operator std::string();

关于c++ - std::string 的转换运算符无法处理赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54621668/

相关文章:

C++:辛>> *字符

c++ - 使用后缀表示法在 C++ 中输入数字

C++ 多行 #if

c++ - 运算符 float*() 是做什么的?

c++ - C++ 中的转换运算符

c# - C#如何制作行为类似于Nullable <T>的类

c++ - std::getline() 如何等同于 bool?

c++ - 嵌套类中用户定义的转换运算符

c++ - Qt信号/插槽实际上如何与.ui文件中的元素耦合?

android - 是否有使用C/C++和SDL对Android进行编程的入门指南?