3

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

这可能吗?

4

1 回答 1

1

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

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

于 2018-05-17T19:28:50.170 回答