如何用BOOST_HANA_ADAPT_ADT定义get / set对?

时间:2018-03-15 10:41:06

标签: c++ boost-hana

我想反省第三方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); })
);

这可能吗?

1 个答案:

答案 0 :(得分:0)

我不确定你到底想要做什么,但是你可以使用像这样的虚拟类型做一些事情:

#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"类型的东西.....