简体   繁体   English

std :: string的转换运算符无法与赋值一起使用

[英]Conversion operator for std::string fails to work with assignment

I am using a proxy type to defer the work until the result is assigned to a variable, it works by using conversion operators on the proxy type. 我正在使用代理类型来推迟工作,直到将结果分配给变量为止,它通过对代理类型使用转换运算符来工作。 When adding an conversion operator overload for std::string , it works for string construction from proxy, but fails to compile for assignment, with the following error message: std::string添加转换运算符重载时,它可用于从代理构造字符串,但无法编译以进行赋值,并显示以下错误消息:

error: ambiguous overload for 'operator=' 错误:“ operator =”的模棱两可的重载

While this question is similar to the one at operator T() not used in assignment , solution there is not applicable here since I am also using templated conversion operator. 尽管此问题类似于分配中未使用的运算符T()处的问题,但解决方案在此处不适用,因为我也使用模板转换运算符。

Below is the snippet: 以下是代码段:

#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? 如何使该代理与字符串分配一起使用?

How can this proxy be made to work with the string assignment? 如何使该代理与字符串分配一起使用?

The compiler is unable to tell what conversion you want. 编译器无法告知您要进行什么转换。 It could be anything that can be used to construct an std::string - char , char * , std::string , ... 它可以是任何可以用来构造std::string - charchar *std::string ,...的东西。

So the solution is to tell the compiler what you want. 因此解决方案是告诉编译器您想要什么。 Make an explicit operator call: 进行明确的操作员调用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM