9

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

5
  • 2
    @Sergey I can't spot a local variable there? Commented Nov 16, 2016 at 10:03
  • Related. Commented Nov 16, 2016 at 10:04
  • @πάνταῥεῖ Ah, yes, it should be compiled to the data segment. Commented Nov 16, 2016 at 10:04
  • @Sergey: It's not a local variable, it is a string literal. n4296 in 2.3.5 p16 says "Evaluating a string-literal results in a string literal object with static storage duration" (my emphasis). Commented Nov 16, 2016 at 10:06
  • 3
    Unrelated, but having the operator return const string is a pessimisation, because it prevents moving from the returned value. You should change it to just conver to string. Commented Nov 16, 2016 at 10:08

1 Answer 1

2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.