STL 和 Hana 元组之间的转换

Conversions Between STL and Hana tuples

本文关键字:转换 之间 元组 Hana STL      更新时间:2023-10-16
#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::make_tuple(std::ref(x), std::ref(y), std::ref(z)),但这似乎不必要地冗长。

要在hana::tuplestd::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,对吧?现在这是不可能的,看看这个原因。但是,您可以简单地在 hana::for_each 中使用 std::tuple ,前提是您包含上面的适配器标头:

#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'; });
}