Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 220
sagibu Avatar asked Nov 16 '16 09:11

sagibu


1 Answers

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;
}
like image 184
SingerOfTheFall Avatar answered Sep 25 '22 10:09

SingerOfTheFall