Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string-like class with implicit conversion

I have a couple of string-like classes that can be implicitly converted to strings. I have a few uses for these; one example is to hold text that needs to be translated at runtime by gettext:

class TranslatableString
{
public:
  explicit TranslatableString(const char *s) : native_text_(s) {}
  operator const char *() const { return gettext(native_text_); }

  // Or not - see below:
  operator const std::string() const { return gettext(native_text_); }

private:
  const char * const native_text_;
};

Now I'm trying to make using this class as simple as possible (i.e., using it should be as much like a string literal as possible). In particular, I'd like for both of the following sample usages to work:

const TranslatableString HELLO = TranslatableString("Hello, world!");

std::string ExampleA() {
  return HELLO;
}

void ExampleB() {
  std::string s;
  s = HELLO;
}

Is there any way to make both examples work?

  • If I include operator std::string, then ExampleB fails to compile, saying that there's an ambiguity between std::string::operator=(const char *) and std::string operator=(const std::string&) (which makes sense).
  • If I don't include operator std::string, then ExampleA fails to compile; apparently implicitly converting a TranslatableString to const char * to std::string is not allowed, although I don't understand C++'s implicit conversion rules well enough to explain why.
like image 712
Josh Kelley Avatar asked Apr 05 '13 15:04

Josh Kelley


1 Answers

Only one user-defined conversion is allowed in each conversion sequence, that's why you can't go "through" a const char*. (Note that const char* to std::string is also a user-defined conversion).

Do you need the conversion to const char*? Without it (and with coversion to std::string), both examples would work.

It might also be worth considering storing the data as std::string internally, instead of const char*. You wouldn't have to worry about deallocation issues, the data "disappearing" under your hands etc.

like image 85
Angew is no longer proud of SO Avatar answered Sep 30 '22 00:09

Angew is no longer proud of SO