sagibu sagibu - 24 days ago 13
C++ Question

c++ operator string and char* causing ambiguous error

I'm trying to make a class with conversion operators to string and char*, this makes ambiguous call error when trying to create a string.
assume i have the following class:

class A
{
public:
A(){};
operator const char*() const { return "a" };
operator const string() const { return "b" };
}


and the following main programs:

int main()
{
A a;
string b = string(a);
return 0;
}


this causing ambiguous call error to basic_string(A&)
also tried the following:

class A
{
public:
A(){};
operator const char*() const { return "a" };
explicit operator const string() const { return "b" };
}

int main()
{
A a;
string b = static_cast<string>(a);
return 0;
}


this causing the same error. I need to have both operators in my code, how can i
make this work?

note: using string b = a works but I need the string(a) format to work aswell

note 2: not using explicit keywork makes operator= ambiguous

Answer

You need to make them both explicit and use static_cast:

class A
{
public:
    A(){};
    explicit operator const char*() const { return "a"; };
    explicit operator const string() const { return "b"; };
};

int main()
{
    A a;
    string b = static_cast<string>(a); // works, b now has "b" as value
    const char * c = static_cast< const char *>(a); // works too, c now has "a" as value
    return 0;
}