Martin Schlott
Martin Schlott

Reputation: 4547

Error during cast of an object to std::string with proper operator-overloading

Follwing short programm will run perfect with VS 2013 and reach the marked point. But in XCode the compiler will show an error due ambiguous constructor. How to work around?

#include <iostream>
#include <string>

class atest
{
public:
    explicit operator const char *()
    {
        return "";
    }
    template<class T> operator T()
    {

    }
    operator std::string()
    {
        return std::string("Huhuhu");
    }
    template<class T> atest &operator =(T value)
    {

    }
    atest &operator =(const std::string &value)
    {
        return *this; // I want to reach this point
    }
};

int main(int argc, char* argv[])
{
    atest tst;

    //   auto a = (std::string)tst;
    std::string astr;

    // do some stuff

    astr=tst; // I wanna keep this line

    return 0;
}

Clang is not able to distinguish between different constructor where VS2013 is taking the right one. I search now for a way to exclude the "const char *" template of the assignment operator.

Upvotes: 1

Views: 61

Answers (2)

rockoder
rockoder

Reputation: 747

I think you have written far too many overloaded functions. The only function you need is this:

operator std::string()
{
    return std::string("Huhuhu");
}

Comment rest all and your code would work just fine.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

std::string have multiple constructors taking single arguments, and since you provide both a conversion operator for std::string and a generic any-type conversion operator, the compiler simply don't know which constructor to pick.

Upvotes: 1

Related Questions