#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::tuple
在hana::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/