adapter - 是否可以融合适应基类?

标签 adapter boost-fusion

是否可以像成员一样融合调整基类?

首先,这是文档示例,与新案例并排:

#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

struct employee{
    std::string name;
    int age;
};

BOOST_FUSION_ADAPT_STRUCT(
    employee,
    (std::string, name)
    (int, age))

struct employee2 : std::string{
    int age;
};

BOOST_FUSION_ADAPT_STRUCT(
    employee2,
    (std::string, name) ???
    (int, age))


int main(){}

我应该在???行中放入什么。

目前我找到的唯一解决方案就是这样做,但是 1) 我必须让所有成员都具有 getter 和 setter 函数 2) 似乎有点矫枉过正。

#include <boost/fusion/adapted/adt/adapt_adt.hpp>
struct employee2 : std::string{
    int age;
    void set_base(std::string const& age_){std::string::operator=(age_);}
    std::string const& get_base() const{return static_cast<std::string const&>(*this);}
    void set_age(int const& age_){age = age_;}
    int const& get_age() const{return age;}
};

BOOST_FUSION_ADAPT_ADT(
   employee2,
    (std::string, std::string, obj.get_base(), obj.set_base(val))
    (int, int, obj.get_age(), obj.set_age(val))
)

最佳答案

好吧,看起来(通过实验)可以将各种有效表达式放入 BOOST_FUSION_ADAPT_ADT 中。我不太确定这是否是最佳的(例如,融合是否会在访问元素时复制),因此欢迎其他答案。

#include <boost/fusion/adapted/adt/adapt_adt.hpp>
BOOST_FUSION_ADAPT_ADT(
   employee2,
    (static_cast<std::string const&>(obj), obj.std::string::operator=(val))
    (obj.age, obj.age = val)
)

int main(){

    employee2 e2;
    boost::fusion::at_c<0>(e2) = "Pepe";
    boost::fusion::at_c<1>(e2) = 37;

    cout << e2 << " " << e2.age <<'\n';

}

这可能会阻止某些副本,并且似乎在更多情况下有效(例如 boost::fusion::copy),但我不确定为什么:

BOOST_FUSION_ADAPT_ADT(
   employee2,
    (std::string, std::string const&, obj, obj.std::string::operator=(val))
    (int, int const&, obj.age, obj.age = val)
)

关于adapter - 是否可以融合适应基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39646310/

相关文章:

java - getView 未在自定义适配器中调用

android - Listview 中的 Picasso 和 Holders 具有可变高度

c++ - 结构减去填充的编译时大小

c++ - boost fusion/MPL : convert type from sequence to sequence of equivalent any_range's

c++ - boost::phoenix::insert 的评估结果

c++ - 是否可以反向使用 boost fusion map,也就是 key 是 567,value 是 type ?

java - 在 Java 中编写适配器时的最佳实践

PHP 设计模式 - 继承与适配器模式?

java - 当我删除某些内容时,ListView 不会刷新

c++ - boost::fusion 的目的是什么?