C++/CLI has a System::Object class to serve this purpose, but I can't seem to find one in the standard library. Basically I'm writing a set of classes, and I would like the base class to store a vector of std::stringin a content property, but derived classes might need to store a vector of something else (perhaps even one of my own classes). It might seem like an odd goal, but I'm writing a some file access classes to let me more easily manipulate files of different formats. The base File class will store each line in a string, as part of the vector - but a class for JSON, for instance, might need to store JS-Style collections/objects, etc.
The only way I could think to do this is to have the content property a vector of objects (or some other universal base class - I can derive any custom classes from it for polymorphism's sake too) and then cast it back into whatever type is necessary depending on the type of child object that is being used. I soon discovered that I couldn't find any mention of std::object (or similar) anywhere.
This example should demonstrate what I'm trying to do:
class File {
protected:
std::vector<std::object> _content;
public:
//Contructors/methods/etc.
std::string getItemAt(size_t index) {
return static_cast<std::string>(this->_content[index]);
}
void setItemAt(size_t index, std::string value) {
this->_content[index] = static_cast<std::object>(value);
}
};
class JSONFile: File {
public:
//Constructors/methods/etc.
SomeObject getItemAt(size_t index) {
return static_cast<SomeObject>(this->_content[index]);
}
void setItemAt(size_t index, SomeObject value) {
this->_content[index] = static_cast<std::object>(value);
}
};
Note that this example assumes that std::object exists, and that SomeObject would be whatever is used to handle the JSON (again, for example - this could be anything) data. SomeObject would obviously derive from std::object.
Any suggestions would be greatly appreciated, or if I'm going completely the wrong way about this, any feedback as to how I could do it so that the std::object thing isn't necessary would be greatly appreciated :)
No.
Because C++ is all about "you only pay for what you use".
What would the interface of std::object look like? If there were any member functions, those would have to be virtual to be of any use, resulting in a runtime cost because of dynamic dispatch.
If the hypothetical std::object was an empty class, what could you do with a std::object reference? Not much, since it wouldn't have any member functions to call. Why make everything derive from a single base when they have nothing in common.
If you really need a base for all of your classes, you can always write one. But note that doing so might not be a good design decision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With