FeatherMC/src/config/Property.h

84 lines
1.9 KiB
C
Raw Normal View History

#pragma once
#include "Properties.h"
#include "ServerProperties.h"
#include <string>
#include <string_view>
#include <unordered_map>
#include <functional>
#include <ostream>
using std::string;
using std::string_view;
using std::unordered_map;
namespace Feather::Config
{
template <typename T>
class Property
{
public:
Property(string_view key) : key(key) {}
Property(string_view key, T defaultValue) : key(key), value(defaultValue) {}
2020-07-31 01:48:48 +01:00
Property(string_view key, std::function<T(T)> op, T defaultValue) : key(key), value(defaultValue), op(op) {}
void Init(Properties *properties)
{
try
{
SetValue(properties->Get<T>(key));
}
2020-07-31 01:48:48 +01:00
catch (const std::out_of_range& err)
{
2020-08-13 01:58:24 +01:00
// ignore unreferenced local var
(void)err;
// process default value from constructor
SetValue(value);
}
}
2020-07-31 01:48:48 +01:00
void SetValue(T value)
{
if (op) {
this->value = op(value);
} else {
this->value = value;
}
}
2020-07-31 01:48:48 +01:00
T GetValue() { return value; }
// Property<T> can be automatically cast to T
2020-08-07 05:49:29 +01:00
inline operator T() const { return value; }
inline string ToString() const { return std::to_string(value); }
string_view key;
private:
T value = T();
std::function<T(T)> op;
};
template <>
inline string Property<string>::ToString() const
{
return value;
}
template <>
inline string Property<bool>::ToString() const
{
return value ? "true" : "false";
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const Property<T>& prop)
{
os << prop.key << "=" << prop.ToString();
return os;
}
2020-08-01 00:57:33 +01:00
}