I would like to create a storage object to/from which I can set/get a property of various types in a software application. (Let's just say the property is a string.) If an attempt is made to retrieve a property for some type T for which no property was previously stored, I want the property returned for the most derived type that is a base class of T. And I would like all this without any special requirements on the class types for which properties are stored.
So basically, it should look something like this.
class Store
{
public:
template <class T> void put(const string& property) { /* MAGIC HERE */ }
template <class T> string get() const { /* MORE MAGIC */ }
};
class X {};
class Y : public X {};
class Z : public Y {};
int main()
{
Store store;
store.put<X>("x");
store.put<Z>("z");
cout << store.get<X>() << endl;
cout << store.get<Y>() << endl;
cout << store.get<Z>() << endl;
return 0;
}
And the output should look like this:
x
x
z
Is this even possible with C++? It would be a snap with java reflections.
Aucun commentaire:
Enregistrer un commentaire