如何为属性类实现泛型访问器

时间:2014-01-26 20:42:27

标签: c++ templates c++11 properties

如何实现属性类的通用访问器及其默认值?

我粗略地认为它看起来如下:

template<typename Type, 
         typename Getter = /* How to implement a default setter? */
         typename Setter = 
class Property {
    Getter get; /* Is this right? How is it called then? */
    Setter set;

    Property(Type value, Getter getter, Setter setter) ...
};

Getter和Setter应该能够作为lambdas给出。这是正确的方法,我该如何继续?

2 个答案:

答案 0 :(得分:1)

你可以同意getter和setter的某种结构接口,然后实现这样的东西:

template <typename T> struct default_getter
{
    T & operator()(T & x) const { return x; }
    T const & operator()(T const & x) const { return x; }
};

template <typename T> struct default_setter
{
    template <typename U>
    void operator()(T & x, U && u) const { x = std::forward<U>(u); }
};

template <typename T,
          typename Getter = default_getter<T>,
          typename Setter = default_setter<T>>
class Property
{
    struct PropertyImpl : Getter, Setter
    { 
         T value;
    };

    PropertyImpl impl;
public:
    template <typename U>
    void set(U && u)
    {
        static_cast<Setter &>(impl)(impl.value, std::forward<U>(u));
    }

    T & get()
    {
        static_cast<Getter &>(impl)(impl.value);
    }

    T const & get() const 
    {
        static_cast<Getter const &>(impl)(impl.value);
    }
};

现在您可以这样使用它:

struct Foo
{
    Property<Bar> bar;
};

Foo x;
x.bar.get();
x.bar.set(10);

答案 1 :(得分:0)

我会使用std::function提出解决方案。

template<typename T>
struct Property
{
   typedef std::function<T()> GetterFunc;
   typedef std::function<void(const T&)> SetterFunc;

   Property (T value, GetterFunc getter, SetterFunc setter) 
   : m_getter(getter)
   , m_setter(setter) 
   {
   }

   Property(T value) 
   : m_getter( [value](){ return value; }
   , m_setter ( [](const T&) { } ) // I have know clue what behaviour you want here
   {
   }

   T Get() { return m_getter(); }
   void Set(const T& value) { m_setter(value); }

private:

    GetterFunc m_getter;
    SetterFunc m_setter;
}