Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <functional>
- #include <memory>
- #include <unordered_map>
- template<typename T> using GetterFunc_t = std::function<T()>;
- template<typename T> using SetterFunc_t = std::function<void(const T&)>;
- class IProperty {
- public:
- virtual ~IProperty() {}
- };
- template <typename T>
- class Property : public IProperty {
- public:
- Property(const GetterFunc_t<T>& getter, const SetterFunc_t<T>& setter) :
- getter(getter),
- setter(setter)
- { }
- T get()
- {
- return getter();
- }
- void set(const T& value)
- {
- setter(value);
- }
- private:
- GetterFunc_t<T> getter;
- SetterFunc_t<T> setter;
- };
- class MetaObject {
- public:
- template<typename T>
- void meta_register(const std::string& propertyName, T& propertyRef)
- {
- GetterFunc_t<T> getter = [&propertyRef]() -> T { return propertyRef; };
- SetterFunc_t<T> setter = [&propertyRef](const T& newValue) { propertyRef = newValue; };
- properties[propertyName] = std::make_unique<Property<T>>(getter, setter);
- }
- template<typename T>
- T getProperty(const std::string& propertyName)
- {
- auto property = findProperty<T>(propertyName);
- if (property) {
- return property->get();
- }
- return T();
- }
- template <typename T>
- void setProperty(const std::string& propertyName, const T& value)
- {
- auto property = findProperty<T>(propertyName);
- if (property) {
- property->set(value);
- }
- }
- private:
- template <typename T>
- Property<T>* findProperty(const std::string& propertyName)
- {
- auto it = properties.find(propertyName);
- if (it != properties.end()) {
- auto concreteProperty = dynamic_cast<Property<T>*>(it->second.get());
- return concreteProperty;
- }
- return nullptr;
- }
- std::unordered_map<std::string, std::unique_ptr<IProperty>> properties;
- };
- // EXAMPLE CLASS
- class Animation : public MetaObject
- {
- public:
- Animation()
- {
- meta_register("name", name);
- meta_register("isLooped", isLooped);
- meta_register("frameCount", frameCount);
- }
- private:
- std::string name;
- bool isLooped;
- int frameCount;
- };
- int main()
- {
- Animation a;
- // and now I can do this!
- a.setProperty("name", std::string("walk"));
- a.setProperty("isLooped", true);
- a.setProperty("frameCount", 100);
- std::cout << "Name = " << a.getProperty<std::string>("name") << std::endl;
- std::cout << "isLooped = " << a.getProperty<bool>("isLooped") << std::endl;
- std::cout << "frameCount = " << a.getProperty<int>("frameCount") << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement