Background:
I would like to create a settings class in C++ that mimics .NET's Properties.Settings.Default.
For people that don't know what is it, basically it's a singleton class in which you can store application settings.
My attempt:
The singleton class: so far so good, thanks to C++ Singleton design pattern
The properties: this is where I would like to get some infrastructure help
Here's a typical property with a getter and a setter:
QString GetTheme()
{
return GetValue(ThemeKey, "Material").toString();
}
void SetTheme(const QString &value)
{
SetValue(ThemeKey, value);
}
This works but you might already guess my question: How to avoid all this boilerplate code ?
Basically what I would like to achieve is some sort of one-liner to define a property, like:
// pseudo code ahead
// this property is of type QString and whose default value is "Material"
property<QString, "Material"> Theme;
// ideally it should be usable like that:
auto theme = Settings::Current.Theme(); // getter
Settings::Current.Theme("..."); // setter
There will be different type of properties, such as int
, bool
, QString
etc.
Question:
Can C++ templates somehow help solving this problem or should I write a good old macro?
I am also ready to accept any decent alternative to this approach.
EDIT:
I just realized that I didn't fully explained myself, sorry about that.
The value of these properties will be fetched by Qt's QSettings
class such as:
QSettings settings;
settings.setValue("editor/wrapMargin", 68);
Below I am pasting my current implementation so you have a better understanding of how properties' values are fetched:
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QSettings>
#include <QString>
class Settings
{
private:
Settings()
{
}
QSettings Store;
QVariant GetValue(const QString &key, const QVariant &defaultValue = QVariant())
{
return Store.value(key, defaultValue);
}
void SetValue(const QString &key, const QVariant &value)
{
Store.setValue(key, value);
}
static const QString ThemeKey;
public:
Settings(Settings const&) = delete;
void operator=(Settings const&) = delete;
static Settings& Current()
{
// https://stackoverflow.com/a/1008289/361899
static Settings instance;
return instance;
}
QString GetTheme()
{
return GetValue(ThemeKey, "Material").toString();
}
void SetTheme(const QString &value)
{
SetValue(ThemeKey, value);
}
};
const QString Settings::ThemeKey = "ThemeKey";
#endif // SETTINGS_H