非类型模板参数的一个应用场景
原始代码
#include <QCoreApplication>
#include <QSettings>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings settings;
settings.setValue("length", 100);
cout<<settings.value("length").toInt()<<endl;
return a.exec();
}
以上代码是使用QSettings设置配置信息,调用配置信息的一个简单实例。从这里看,似乎没有什么可以改的。不过使用下面的代码之后,配置和获取信息将更加直观。如下
新建一个Settings类包装一下QSettings
头文件和源文件如下
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QObject>
#include <QString>
#include <QSettings>
class Settings : public QObject
{
Q_OBJECT
public:
static const char length[];
public:
explicit Settings(QObject *parent = 0) : QObject(parent) {
}
template<const char* name, int deflt = 0>
class IntRef {
public:
operator int() const {
return QSettings().value(name, deflt).toInt();
}
IntRef& operator = (int i) {
QSettings().setValue(name, i);
return *this;
}
};
IntRef<length, 20> len;
};
#endif // SETTINGS_H
#include "settings.h"
const char Settings::length[] = "len";
测试
#include <iostream>
using namespace std;
#include <QCoreApplication>
#include <QSettings>
#include "settings.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSettings::setDefaultFormat(QSettings::IniFormat);
Settings settings;
cout<< settings.len << endl;
settings.len = 100;
cout<< settings.len << endl;
int test = settings.len;
cout << test << endl;
return a.exec();
}
使用Settings之后,就可以更直观的操作配置参数了。省去了相对繁琐的setvalue和value操作,重载了=和(),可以像操作基本数据类型一样操作Settings