dimanche 28 mai 2023

Should My string class supply implicit conversion to std::string

I defined a string class and one of its constructors accepts std::string, that is to say std::string can be directly converted to my string. And for some reason, I want to provide an implicit conversion method for my string to std::string. It looks like:

class MyString {
public:
  MyString(const std::string& str) : data(str) {}

  operator const std::string& () const {
    return data;
  }

private:
  std::string data;
};

After I provided a method for implicit conversion to std::string, I only found a compilation error: the type selection error of the c++ ternary expression. Something like: b ? std::string("") : MyString("").

But I worry that there may be some unknown hazards in being able to convert from std::string to MyString, and directly from MyString to std::string. Is it OK? Why? Thanks All.

Aucun commentaire:

Enregistrer un commentaire