我正在尝试编写一个可以在C ++中模拟C#属性的类,我想出了下面的代码。它适用于POD类型(虽然声明语法当然不像C#那样简洁),但是我想不出让getter返回除存储对象类型之外的东西的方法(同样,setter必须采用完全是存储的类型)。我希望能够指定一个返回(可能是const)引用的getter,而不是副本。当然,我想在编译时使用模板魔术来推断它,而不是为每个排列设置一个单独的类。
template<typename owner, typename propertyType, propertyType (owner::*getter)() const, void (owner::*setter)(propertyType)>
class property
{
friend class property<owner, propertyType, getter, nullptr>;
private:
owner &mOwner;
public:
property(owner &owner)
: mOwner(owner)
{
}
template<typename otherProperty>
property(const otherProperty &other)
: mOwner(other.mOwner)
{
}
property &operator=(const property &other)
{
assert(setter);
(mOwner.*setter)((other.*)getter());
return *this;
}
property &operator=(propertyType value)
{
assert(setter);
(mOwner.*setter)(value);
return *this;
}
template<typename otherProperty>
property &operator=(const otherProperty &other)
{
assert(setter);
(mOwner.*setter)(other);
return *this;
}
operator propertyType() const
{
assert(getter);
return (mOwner.*getter)();
}
};
class Test
{
typedef std::array<std::array<int, 4>, 4> array_type;
private:
int mId;
array_type mArray;
int GetId() const;
void SetId(int newId);
// I would rather return a reference here, not a copy
array_type GetArray() const;
public:
property<Test, int, &GetId, &SetId> Id;
property<Test, int, &GetId, nullptr> ReadOnlyId;
// if GetArray returned a reference, this line would fail to compile
property<Test, array_type, &GetArray, nullptr> Array;
public:
Test()
: mId(0)
, Id(*this)
, ReadOnlyId(Id)
, Array(*this)
{
}
};