Skip to content

Instantly share code, notes, and snippets.

@native-m
Created July 7, 2021 13:42
Show Gist options
  • Save native-m/f40112cb2655427664c131a8637cc39b to your computer and use it in GitHub Desktop.
Save native-m/f40112cb2655427664c131a8637cc39b to your computer and use it in GitHub Desktop.

Revisions

  1. native-m created this gist Jul 7, 2021.
    52 changes: 52 additions & 0 deletions Property.h
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    #include <functional>

    template<typename T>
    class Property
    {
    public:
    using GetterFn = T&();
    using SetterFn = void(const T&);

    template<typename Getter, typename Setter>
    constexpr Property(Getter&& getter, Setter&& setter) noexcept :
    m_getter(getter),
    m_setter(setter)
    {
    }

    Property& operator=(const T& value)
    {
    m_setter(value);
    return *this;
    }

    operator T& ()
    {
    return m_getter();
    }

    operator const T& () const
    {
    return m_getter();
    }

    private:
    std::function<GetterFn> m_getter;
    std::function<SetterFn> m_setter;
    };

    /*
    Usage
    _____
    In-class declaration:
    T = any type
    Property<T> myProp {
    [&]() -> T& { ... }, // Getter
    [&](const T& value) { ... } // Setter
    };
    Property access example:
    other = myProp; // assign other variable from property
    myProp = other; // assign property from other variable
    */