c++ - STL 和 Hana 元组之间的转换

标签 c++ boost-hana

#include <boost/hana.hpp>
#include <iostream>
#include <tuple>

namespace hana = boost::hana;

int main()
{
    int x{7};
    float y{3.14};
    double z{2.7183};
    auto t = hana::to<hana::tuple_tag>(std::tie(x, y, z));
    hana::for_each(t, [](auto& o) { std::cout << o << '\n'; });
}

hana 实现这一目标的方法是什么?我意识到我可以使用: hana::make_tuple(std::ref(x), std::ref(y), std::ref(z)),但这似乎不必要地冗长。

最佳答案

hana::tuple 之间进行转换和一个 std::tuple ,您需要制作 std::tuple有效的 Hana 序列。自 std::tuple开箱即用,您只需包含 <boost/hana/ext/std/tuple.hpp> 。因此,以下代码有效:

#include <boost/hana.hpp>
#include <boost/hana/ext/std/tuple.hpp>
#include <iostream>
#include <tuple>
namespace hana = boost::hana;

int main() {
    int x{7};
    float y{3.14};
    double z{2.7183};
    auto t = hana::to<hana::tuple_tag>(std::tie(x, y, z));
    hana::for_each(t, [](auto& o) { std::cout << o << '\n'; });
}

请注意,您还可以使用 hana::to_tuple为了减少冗长:

auto t = hana::to_tuple(std::tie(x, y, z));

话虽这么说,因为您正在使用 std::tie ,您可能想创建一个 hana::tuple包含引用文献,对吗?目前这是不可能的,请参阅 this由于这个原因。但是,您可以简单地使用 std::tuplehana::for_each ,前提是您包含上面的适配器 header :

#include <boost/hana.hpp>
#include <boost/hana/ext/std/tuple.hpp>
#include <iostream>
#include <tuple>
namespace hana = boost::hana;

int main() {
    int x{7};
    float y{3.14};
    double z{2.7183};
    auto t = std::tie(x, y, z);
    hana::for_each(t, [](auto& o) { std::cout << o << '\n'; });
}

关于c++ - STL 和 Hana 元组之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34317634/

相关文章:

c++ - Boost Hana 实现自定义序列

c++ - 带 bo​​ost::hana 的 SFINAE 模板构造函数

c++ - 这个线程会变成僵尸吗

c++ - C/C++ 更好的写法?

c++ - 使用 boost::hana 创建一个大的编译时间映射

c++ - 如何对数字元组应用 Action 元组?

c++ - 多态性 - "expected class name before { token"错误

c++ - 为什么在 std::optional 的某些实现中存在虚拟 union 成员?

c++ - 使用 system() 执行命令返回返回值的 256 倍 (<< 8)。这有什么意义呢?

c++ - 如何将 boost::hana::unpack 与构造函数一起使用,而不是函数?