C++ 初始化boost::fusion::map值

C++ 初始化boost::fusion::map值,c++,boost,fusion,C++,Boost,Fusion,我有一个像这样的boost::fusion::map: struct bar {}; struct baz {}; template<typename... Args> struct foo { foo(bar &, baz &) {} }; template<typename... T> using MapEntry = boost::fusion::pair<boost::mpl::set<T...>, foo<T.

我有一个像这样的
boost::fusion::map

struct bar {};
struct baz {};

template<typename... Args>
struct foo
{
    foo(bar &, baz &) {}
};

template<typename... T>
using MapEntry = boost::fusion::pair<boost::mpl::set<T...>, foo<T...>>;

using Map = boost::fusion::map<
            MapEntry<int, bool, double>,
            MapEntry<std::string>,
            MapEntry<int64_t, uint32_t>,
            MapEntry<char, uint64_t>
            // ...
            >;

但这是非常多余的。是否可以使此代码更干净?

首先创建一个函数来创建
MapEntry

template<typename E, typename... Args>
E make_map_entry(Args &&...args)
{
    return boost::fusion::make_pair<E::first_type>(E::second_type(std::forward<Args>(args)...));
}
然后我们就可以写了

int main()
{
    bar bar_;
    baz baz_;

    Map map(make_map<Map>(bar_, baz_));

    return 0;
}
intmain()
{
酒吧酒吧;
巴兹巴兹;
地图(制作地图(条形图、巴兹图));
返回0;
}

您可以使用自定义输入工厂:

struct bound_factory {
    bar& bar_;
    baz& baz_;

    template <typename... T> auto entry() const {
         return boost::fusion::make_pair<boost::mpl::set<T...>>(foo<T...>(bar_, baz_));
    }
};
struct-bound\u工厂{
酒吧&酒吧;
巴兹&巴兹;
模板自动输入()常量{
返回boost::fusion::make_对(foo(bar_uu,baz_u));
}
};
然后您可以按如下方式使用:

int main()
{
    bar bar_;
    baz baz_;

    bound_factory f { bar_, baz_ };

    Map map_(
        f.entry<int, bool, double>(),
        f.entry<std::string>(),
        f.entry<int64_t, uint32_t>(),
        f.entry<char, uint64_t>()
    );
}
intmain()
{
酒吧酒吧;
巴兹巴兹;
边界工厂{bar_uuu,baz_uu};
地图_(
f、 entry(),
f、 entry(),
f、 entry(),
f、 条目()
);
}
Clippy模式 看起来您可能正在创建一个依赖项注入框架。请注意这个相当不错的图书馆提案:


为什么你认为这是不可能的?你试了什么?你在哪里被卡住了?现在我只找到了
Map-Map-pair(boost::fusion::make-pair(foo(bar,baz)),boost::fusion::make-pair(foo(bar,baz)),boost::fusion::make-pair(foo(bar,baz)),boost::fusion::make-pair(foo(bar,baz))/但它太过冗余,解决方案很好,但需要两次描述映射条目的类型。
struct bound_factory {
    bar& bar_;
    baz& baz_;

    template <typename... T> auto entry() const {
         return boost::fusion::make_pair<boost::mpl::set<T...>>(foo<T...>(bar_, baz_));
    }
};
int main()
{
    bar bar_;
    baz baz_;

    bound_factory f { bar_, baz_ };

    Map map_(
        f.entry<int, bool, double>(),
        f.entry<std::string>(),
        f.entry<int64_t, uint32_t>(),
        f.entry<char, uint64_t>()
    );
}