gpt4 book ai didi

c++ - 如何为属性类实现通用访问器

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:09 24 4
gpt4 key购买 nike

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

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

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 应该能够作为 lambda 表达式给出。这是正确的方法吗?我该如何继续?

最佳答案

您可以同意某种用于 getter 和 setter 的结构接口(interface),然后实现如下内容:

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);

关于c++ - 如何为属性类实现通用访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21368929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com