You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

83 lines
1.9 KiB

#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) {}
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));
}
catch (const std::out_of_range& err)
{
// ignore unreferenced local var
(void)err;
// process default value from constructor
SetValue(value);
}
}
void SetValue(T value)
{
if (op) {
this->value = op(value);
} else {
this->value = value;
}
}
T GetValue() { return value; }
// Property<T> can be automatically cast to T
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;
}
}