PDA

View Full Version : Static Init of a QMap



Scorp1us
6th March 2007, 16:03
In python, which I know is 100% runtime, I can initialize a dictionary as:


d={'a':1, 'b':2}

so


d['a']=1

I have a need to have a constant QMap, and I'd rather not have to call a function to initialize it, since that will break the const protection. I'd like the compiler to make it for me.

Is there any way to do that qith a QMap? (Or other similar class)

jpn
27th March 2007, 21:06
// i guess with QMap you have to workaround it like this:
static QMap<char, int> myValues() {
QMap<char, int>map;
map.insert('a', 1);
map.insert('b', 2);
return map;
}
static const QMap<char, int> MY_MAP = myValues();

// with QList it would be this simple:
static const QList<int> MY_LIST = QList<int>() << 1 << 2;

pauli
22nd June 2010, 15:08
#include <QMap>
#include <QString>
#include <QPair>

template <class Key, class T> class InitializableQMap : public QMap<Key,T>
{
public:
inline InitializableQMap<Key,T> &operator<< (const QPair<Key,T> &t)
{ insert(t.first,t.second); return *this; }
};

class MyClass
{
public:
static const InitializableQMap<QString, int> MY_STATIC_CONST_MAP;
};

const InitializableQMap<QString,int> MyClass::MY_STATIC_CONST_MAP = InitializableQMap<QString,int>()
<< QPair<QString,int>("key1",3)
<< QPair<QString,int>("key2",2)
;