However, this is a bad idea, because the lifetime of the const char * is constrained to the lifetime of the std::string instance it was cast from--and that semantic gets lost if the class can silently substitute for any old const char *.
C++ supports the "explicit" keyword, but it can only be attached to constructors. If it could be attached to operators as well, we might have a solution, because we could only cast deliberately--not on accident.
I'm not sure how good of an idea this is. Instead of supporting the "explicit" mark in intent, it might be better to support an "implicit" one; perhaps explicit should be the unmarked case. Or perhaps we don't need this at all...
Theoretically, a std::string could support an operator that allowed it be cast to a const char *:
class string { public: ... operator const char *() const; ... };
However, this is a bad idea, because the lifetime of the const char * is constrained to the lifetime of the std::string instance it was cast from--and that semantic gets lost if the class can silently substitute for any old const char *.
C++ supports the "explicit" keyword, but it can only be attached to constructors. If it could be attached to operators as well, we might have a solution, because we could only cast deliberately--not on accident.
I'm not sure how good of an idea this is. Instead of supporting the "explicit" mark in intent, it might be better to support an "implicit" one; perhaps explicit should be the unmarked case. Or perhaps we don't need this at all...