Error during cast of an object to std::string with

2019-07-29 01:16发布

问题:

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.

回答1:

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.



回答2:

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.