gpt4 book ai didi

c++ - 花 : How do I create a tuple of types from a variant?

转载 作者:太空狗 更新时间:2023-10-29 19:48:06 27 4
gpt4 key购买 nike

如果我有一个变体,像这样:

using my_variant = boost::variant<int, bool, std::string>;

有没有一种简单的方法可以将变体可以包含的类型提取到 Boost.Hana 元组中,以便满足以下条件:

using boost::hana::type;
static_assert(std::is_same<my_tuple, boost::hana::tuple<type<int>, type<bool>, type<std::string>>>{});

最佳答案

以下将适用于 develop (从 e13d826 开始):

#include <boost/hana.hpp>
#include <boost/hana/ext/boost/mpl.hpp>
#include <boost/variant.hpp>
#include <string>
namespace hana = boost::hana;


using my_variant = boost::variant<int, bool, std::string>;

constexpr auto my_tuple = hana::to<hana::tuple_tag>(my_variant::types{});

// Note:
// In general, don't use std::is_same to compare hana::tuple; use == in
// because it will also work if the tuple contains hana::basic_types.
static_assert(my_tuple == hana::tuple_t<int, bool, std::string>, "");

什么 e13d826确实添加了对 mpl::list 的支持;只有mpl::vector之前支持过,boost::variant<>::typesmpl::list .这就是为什么我的回答花了一段时间才出来;我正在实现 :-)。

编辑

我没有解释为什么要使用 constexpr auto my_tuple = ...而不是 using my_tuple = decltype(...) .好吧,原因很简单,因为知道 my_tuple 的类型并不是真的有用,因为你不能依赖它。事实上,如果您查看 hana::type 的文档,上面写着你不能依赖hana::type<T>是任何具体的。这有充分的理由,但从可用性的角度来看,这意味着您不能依赖 hana::tuple<hana::type<...>, ...> 的类型。也可以是任何特定的。在进行类型级计算时,更喜欢值级编码(因此 auto my_tuple = ... )而不是类型级编码。这是 Hana 相对于 MPL 和 friend 的特殊性,你应该尽可能地坚持它,否则你会发现 Hana 真的很笨拙(因为没有考虑到这一点)。

关于c++ - 花 : How do I create a tuple of types from a variant?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33679142/

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