gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:45:38 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com