切换示例作为惯用的boost :: hana

时间:2017-01-16 00:58:08

标签: c++ boost template-meta-programming c++17 boost-hana

引言的real world example可以构建而不会回退到原始递归吗?

  

当然,我们可能会以复杂的方式将Hana算法交织在一起,......

为什么这么复杂? - 我猜这个例子生成的代码经常发生。

我对该项目和谷歌进行了一些研究,但找不到任何替代实施方案。

我自己进行了实验:

template <typename Any>
auto switch_(Any& a) {
  return [&a](auto ...cases_) {
    auto cases = hana::make_tuple(cases_...);
    auto default_ = hana::find_if(cases, [](auto const& c) {
      return hana::first(c) == hana::type_c<default_t>;
    });
    static_assert(default_ != hana::nothing, "switch is missing a default_ case");
    auto rest = hana::filter(cases, [](auto const& c) {
      return hana::first(c) != hana::type_c<default_t>;
    });
    auto& type_idx = a.type();
    auto found = hana::find_if(rest, [&](auto const& c) {
      using T = int; // typename decltype(+hana::first(c))::type;
      return hana::bool_c<typeid(int) == type_idx>;
      // return hana::bool_c<false>;
    });
    if constexpr (found == hana::nothing) {
        return hana::second(*default_)();
    }
    else {
        using T = typename decltype(+hana::first(*found))::type;
        return hana::second(*found)(*boost::unsafe_any_cast<T>(&a));
    }
  };
}

find_if无法在编译时解析,因为type_idx仅在运行时已知。

将军hana::fold_left应该能够做到这一点。但我无法弄清楚如何传输所有细节并自动推断出返回类型。

我将不胜感激。

0 个答案:

没有答案