Amirul I
Amirul I

Reputation: 301

C++ Overloading conversion operator hack

I am trying to implement a hack where I am trying to overload return. I will let the code talk.

namespace tcn
{
    class foo
    {
        std::string blah;

    public:
        class proxy
        {
            int intval;
            std::string strval;
        public:
            proxy(int intv, std::string strv) : intval(intv), strval(strv) {};
            operator int() const { return intval; }
            operator std::string() const { return strval; }

        };

        foo();
        ~foo();

        proxy get();
    };

    foo::foo()
    {
        // Create stuff //
    }

    foo::~foo()
    {
        // Destroy stuff //
    }

    foo::proxy foo::get()
    {
        int intval = 911;
        std::string strval = "Hello!?";

        proxy temp(intval, strval);

        return temp;
    }
}



int main()
{
    tcn::foo bar;

    std::string ts = bar.get(); // OK
    int ti = bar.get(); // OK

    ti = bar.get(); // OK

    ts = bar.get(); // Compile error here

    return 0;
}

If I try to compile the code it gives an error like following

error: ambiguous overload for 'operator=' (operand types are 'std::string {aka std::basic_string}' and 'tcn::foo::proxy')
ts = bar.get();

I was wondering how to overcome this. I have seen other ways to implement this by using 'hints' ,But am trying to give an easy interface to the user. So I am looking for a simple assignment from the user side. How else could this be implemented?

Thank you in advance and if this looks lame- I apologize. I am no that good in C++.

Upvotes: 2

Views: 246

Answers (1)

TartanLlama
TartanLlama

Reputation: 65620

The call is ambiguous because std::string::operator= has overloads taking std::string and char. Both of these can be called using a tcn::proxy: the first using the std::string conversion operator, and the second using the int conversion operator followed by an integral conversion.

Usually overload resolution would prefer the implicit conversion sequence with no necessary standard conversions over the one requiring an integral conversion, but this choice is only considered if the two conversion sequences go through the same function. Since you have two separate paths going through two different functions, the call is ambiguous.

The solution is to not use integral conversions for things like that; it just leads to weird edge cases, surprising behaviour and hidden bugs.

Upvotes: 2

Related Questions