LINUX.ORG.RU

Polymorphic QMap


0

1
#include <QMap>
#include <QString>
#include <QDebug>

class Type {
public:
	Type(int i = 5) : _i(i) {}
	int _i;

	virtual int damnIt() { return 1; }
};

class DerivedType : public Type {
public:
	DerivedType(int i = 5) : Type(i) {}

	virtual int damnIt() { return 2; }
};

class Container {
public:
	Container() {}
	virtual Type & operator [](QString propertyName) {
		if (!_properties.contains(propertyName)) _properties[propertyName] = Type();
		return _properties[propertyName];
	}

private:
	QMap<QString, Type> _properties;
};

int main(int, char **) {
	Container c;
	c["hi"] = DerivedType();
	qDebug() << c["hi"].damnIt();
	
	QMap<QString, Type> direct;
	direct["hi"] = DerivedType();
	qDebug() << direct["hi"].damnIt();
}

Output:

$ ./test 
1 
1 

Given the fact that QMap<K,T>::operator[] returns reference why polymorphic principle doesn't work here? What is the correct way to store heterogeneous objects in a container?

Ответ на: комментарий от crowbar

With pointers using the container will be quite inconvenient. I tried to use QMap<QString,Type&> but got long error message from gcc. References in C++ is very unclear subject.

driowria
() автор топика
Ответ на: комментарий от ilammy

I don't think QSharedPointer would help there. I decided to use special class Holder which contains a pointer to Type and overloads operator=(const Type&); The Holder itself inherits from Type but overloads all its methods to use stored pointer's methods. I am using QMap<QString, Holder*> container and do some extra magic in Container operator[]. Looks nice.

driowria
() автор топика
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.