C++ experts - implicit conversion of String to C-string?


Hey C++ gurus!

The String class has the c_str() method to convert to a const char*. However, this means we have lots of duplicated APIs in the code, e.g.

void Spark.subscribe(const char* eventName, ...);


void Spark.subscribe(String eventName, ...) {
    Spark.subscribe(eventName.c_str(), ...);

With the String api simply unwrapping the string to a C-string and calling the C-string function.

We can add an implicit conversion to String, so that it can be used wherever a const char* is expected:

class String {
    // ...
    operator const char*() { return c_str(); }

This works well and allows us to eliminate the API duplicates and gives users more flexibility to use Strings or C-strings as they wish.

And now to the question! Anyone see any reason not to do this?


I’m new to Particle and found myself using c_str() without thinking about whether it was supported or not. As I was studying the firmware reference found here:


I was surprised not to see c_str() included in the APIs. My question … is this a deliberate choice not to document it? Should I not use the c_str() function if I want to ensure portability and long-term support of my code?


c_str() is also a feature used on Arduinos and hence Particle won’t let it die - but I personally prefer the type cast version (const char*)someString as it can be used with both C-strings and String objects.
So refactoring a String into a C-string would not break existing code.