C++ string-like class with implicit conversion -


i have couple of string-like classes can implicitly converted strings. have few uses these; 1 example hold text needs translated @ runtime 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 make using class simple possible (i.e., using should string literal possible). in particular, i'd both of following sample usages work:

const translatablestring hello = translatablestring("hello, world!");  std::string examplea() {   return hello; }  void exampleb() {   std::string s;   s = hello; } 

is there way make both examples work?

  • if include operator std::string, exampleb fails compile, saying there's ambiguity between std::string::operator=(const char *) , std::string operator=(const std::string&) (which makes sense).
  • if don't include operator std::string, examplea fails compile; apparently implicitly converting translatablestring const char * std::string not allowed, although don't understand c++'s implicit conversion rules enough explain why.

only 1 user-defined conversion allowed in each conversion sequence, that's why can't go "through" const char*. (note const char* std::string user-defined conversion).

do need conversion const char*? without (and coversion std::string), both examples work.

it might worth considering storing data std::string internally, instead of const char*. wouldn't have worry deallocation issues, data "disappearing" under hands etc.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -