如何使用BOOST_HANA_ADAPT_ADT定义获取/设置对

How to define get/set pair with BOOST_HANA_ADAPT_ADT?

本文关键字:获取 设置 定义 ADAPT 何使用 BOOST HANA ADT      更新时间:2023-10-16

我想反省第三方 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"类型的东西.....