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?
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).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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With