dimanche 5 novembre 2017

Type conversion by "explicit operator X" for static_cast or toX()?

There are similar previous questions, but all the ones I could find ask different questions:


What are things I should consider when deciding how to implement explicit conversion on a class?

In c++11, I can have an explicit conversion operator:

class myClass {
public:
   explicit operator std::string() const {
      ...
   }
};
const myClass x{...};
std::string str = static_cast<std::string>(x);

Or, I could have a function toX():

class myClass {
public:
   std::string toString() const {
      ...
   }
};
const myClass x{...};
std::string str = x.toString();

Part of me is thinking they're identical, but part of me is thinking I must be missing some scenarios or best practice guidelines.

Granted static_cast allows a call to myClass::explicit operator std::string() or std::string(myClass), but I'm focused on at the point where the decision has been made to have the conversion take place within myClass, like here where std::string() doesn't have a conversion constructor, so this distinction doesn't come into play. And, it also allows casting between inheritance hierarchies, but that doesn't come into play here either.

Aucun commentaire:

Enregistrer un commentaire