Currently, I am do a project to implement Unified API. For example for following code
class Helloworld {
public:
const std::string & str() const { return str_; }
std::string & str() { return str_; }
void str(const std::string & s) { str_ = s; }
private:
std::stringstr_;
};
Apparently, all APIs in Helloworld are very strange, I want to add following
const std::string & GetCRefStr() const { return str_; }
std::string & GetMutableStr() { return str_; }
void SetStr(const std::string & s) { str_ = s; }
For this goal, I use cast from base to derived
class HelloworldWrap : public Helloworld {
public:
const std::string & GetCRefStr() const { return Helloworld::str(); }
std::string & GetMutableStr() { return Helloworld::str(); }
void SetStr(const std::string & s) { Helloworld::str(s); }
// No any member in HelloworldWrap, this class just extend APIs for Helloworld
};
And for using
Helloworld kHW;
HelloworldWrap * GetMutableHelloworld() {
return static_cast<HelloworldWrap *>(&kHW);
}
const HelloworldWrap & GetCRefHelloworld() {
return *(static_cast<HelloworldWrap*>(&kHW));
}
int main() {
GetMutableHelloworld()->SetStr("helloworld");
// balabala
}
It works ok! Does this approach correct??