有点跑题了,但是如果你要在Owner 的每个属性成员中存储Owner 指针,这在内存方面是次优的,即每个属性成员都有一个完全相同的副本Owner*.
在 C++ 中,对象布局在编译时是已知的,因此,给定 Owner 成员的 this 指针,如果成员名称已知,则可以使用 offsetof macro 获取 Owner*。
仍然,要将数据成员名称注入 Owner,必须定义该数据成员,并且在 Owner 中至少占用一个字节,因为 C++ 不允许大小为 0 的数据成员(与空基类优化不同)。
这是一个基于使用offsetof的示例:
#include <utility>
#include <cstddef>
#include <cstdint>
template<class Owner, class T, class Tag = void>
struct Property;
template<class Owner, class T, class Tag>
Owner& get_property_owner(Property<Owner, T, Tag>&); // Must be overloaded for each individual property of a class.
template<class Owner, class T, class Tag>
inline Owner const& get_property_owner(Property<Owner, T, Tag> const& p) {
return get_property_owner(const_cast<Property<Owner, T, Tag>&>(p));
}
template<class Owner, class T, class Tag>
struct Property
{
Property() = default;
Property(Property const&) = delete;
Property& operator=(Property const&) = delete;
template<class U>
Property& operator=(U&& u) {
get_property_owner(*this).property_set(*this, std::forward<U>(u));
return *this;
}
operator T() const {
return get_property_owner(*this).property_get(*this);
}
};
// Convenience macro to save typing boiler plate code.
#define PROPERTY(Owner, Type, Name) \
struct PropertyName_##Name {}; \
Property<Owner, Type, PropertyName_##Name> Name; \
friend Owner& get_property_owner(Property<Owner, Type, PropertyName_##Name>& p) { \
return *reinterpret_cast<Owner*>(reinterpret_cast<uintptr_t>(&p) - offsetof(Owner, Name)); \
}
class WithProperties
{
public:
// Explicitly define a property, begin.
struct TagA {};
Property<WithProperties, int, TagA> a;
template<class T>
friend WithProperties& get_property_owner(Property<WithProperties, T, WithProperties::TagA>& p) {
return *reinterpret_cast<WithProperties*>(reinterpret_cast<uintptr_t>(&p) - offsetof(WithProperties, a));
}
void property_set(Property<WithProperties, int, TagA>& property_a, int value) {}
int property_get(Property<WithProperties, int, TagA> const& property_a) const { return 'a'; }
// Explicitly define a property, end.
// Define a property using the convience macro, begin.
PROPERTY(WithProperties, int, b);
void property_set(Property<WithProperties, int, PropertyName_b>& property_b, int value) {}
int property_get(Property<WithProperties, int, PropertyName_b> const& property_b) const { return 'b'; }
// Define a property using the convience macro, end.
};
int main() {
WithProperties x;
x.a = 1;
x.b = 2;
int a = x.a;
int b = x.b;
static_cast<void>(a);
static_cast<void>(b);
}