简体   繁体   中英

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:

error: ambiguous overload for '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.

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 , ...

So the solution is to tell the compiler what you want. Make an explicit operator call:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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