Further reduce settings.h

Tue, 14 Jun 2022 20:44:07 +0300

author
Teemu Piippo <teemu.s.piippo@gmail.com>
date
Tue, 14 Jun 2022 20:44:07 +0300
changeset 220
a6d937f8c0ac
parent 219
571e85c0d811
child 221
e28f89b8ccdf

Further reduce settings.h

src/settings.h file | annotate | diff | comparison | revisions
--- a/src/settings.h	Tue Jun 14 20:35:11 2022 +0300
+++ b/src/settings.h	Tue Jun 14 20:44:07 2022 +0300
@@ -3,52 +3,55 @@
 #include <QSettings>
 #include "settingdefs.h"
 
-// settingdefs - get name and default value by setting
-static const struct Settingdef
-{
-	const char* name;
-	QVariant defaultValue;
-} settingdefs[] = {
-#define SETTING(NAME, DEFVALUE) {#NAME, QVariant::fromValue(DEFVALUE)},
-#include "settingdefs.h"
-#undef SETTING
-};
-
 // SettingType - get type of setting by enumerator
-template<Setting setting>
-struct SettingType{};
+template<Setting>
+struct SettingInfo{};
 
 #define SETTING(NAME, DEFVALUE) \
 	template<> \
-	struct SettingType<Setting::NAME> \
+	struct SettingInfo<Setting::NAME> \
 	{ \
 		using type = decltype((DEFVALUE)); \
+		static constexpr char name[] = #NAME; \
+		static const auto& defaultValue() { \
+			static const auto value = DEFVALUE; \
+			return value; \
+		}; \
 	};
 #include "settingdefs.h"
 #undef SETTING
 
-template<Setting setting>
-using SettingType_t = typename SettingType<setting>::type;
+template<Setting X>
+using SettingType_t = typename SettingInfo<X>::type;
 static_assert(std::is_same_v<SettingType_t<Setting::DrawAxes>, bool>);
 
+template<Setting X>
+const char* settingName = SettingInfo<X>::name;
+
+template<Setting X>
+inline auto settingDefaultValue()
+{
+	return SettingInfo<X>::defaultValue();
+}
+
 // get() - get setting by enumerator
 template<Setting X>
 inline SettingType_t<X> setting()
 {
-	const Settingdef& def = settingdefs[static_cast<int>(X)];
-	return QSettings{}.value(def.name, def.defaultValue).value<SettingType_t<X>>();
+	static const QVariant defvariant = QVariant::fromValue(settingDefaultValue<X>());
+	const QVariant var = QSettings{}.value(settingName<X>, defvariant);
+	return var.value<SettingType_t<X>>();
 }
 
 // setSetting() - set value of setting
 template<Setting X>
 inline void setSetting(const SettingType_t<X>& value)
 {
-	const Settingdef& def = settingdefs[static_cast<int>(X)];
-	if (value == def.defaultValue.value<SettingType_t<X>>()) {
-		QSettings{}.remove(def.name);
+	if (value == settingDefaultValue<X>()) {
+		QSettings{}.remove(settingName<X>);
 	}
 	else {
-		QSettings{}.setValue(def.name, QVariant::fromValue(value));
+		QSettings{}.setValue(settingName<X>, QVariant::fromValue(value));
 	}
 }
 

mercurial