我想对第三方ADT进行自省(introspection),该ADT定义了用于访问类的“属性”的成对的getter / setter。例如:
struct Echo {
float mix; // read-only, don't ask why.
void set_mix(float mix);
};
我想写:
BOOST_HANA_ADAPT_ADT(Echo,
(mix,
[] (const auto& self) { return self.mix; },
[] (auto& self, float x) { self.set_mix(x); })
);
这可能吗?
最佳答案
我不确定您要做什么,但是可以使用虚拟类型来执行以下操作:
#include "boost/hana.hpp"
struct Echo {
float mix; // read-only, don't ask why.
void set_mix(float mix);
};
//Getter and setter functionality moved into here
struct FakeType
{
Echo* const inner;
FakeType(Echo* inner) : inner(inner){}
operator float() { return inner->mix; }
FakeType& operator=(const float& value) {
inner->set_mix(value);
return *this;
}
};
BOOST_HANA_ADAPT_ADT(Echo,
//Now returns a "FakeType" instead of the float directly
(mix, [](Echo& p) { return FakeType(&p); })
);
FakeType
类处理所有“getter”和“setter”类型的东西。关于c++ - 如何使用BOOST_HANA_ADAPT_ADT定义获取/设置对?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49297306/