c++ - 从 boost fusion 适应结构中获取成员类型列表
问题描述
我有像这样的增强融合适应结构:
struct A {
int x;
double y;
std::string z;
};
BOOST_FUSION_ADAPT_STRUCT(
A,
x,
y,
z
)
我想在编译时迭代适配的类型。例如,如果我有一个包装类型的类:
template <typename T> class Foo { ... };
那么我希望能够在std::tuple<Foo<int>, Foo<double>, Foo<std::string>>
给定我的结构 A 的情况下获得类型。我std::tuple
在这里仅用作示例;它可以是另一个可变参数类型的模板类。
欢迎使用 c++17 解决方案。
解决方案
将适应的融合结构转换为以下内容的助手std::tuple
:
template<class Adapted, template<class ...> class Tuple = std::tuple>
struct AdaptedToTupleImpl
{
using Size = boost::fusion::result_of::size<Adapted>;
template<size_t ...Indices>
static Tuple<typename boost::fusion::result_of::value_at_c<Adapted, Indices>::type...>
Helper(std::index_sequence<Indices...>);
using type = decltype(Helper(std::make_index_sequence<Size::value>()));
};
template<class Adapted, template<class ...> class Tuple = std::tuple>
using AdaptedToTuple = typename AdaptedToTupleImpl<Adapted, Tuple>::type;
验证:
using AsTuple = AdaptedToTuple<A>;
static_assert(std::is_same_v<std::tuple<int, double, std::string>, AsTuple>);
将元函数应用于元组中的每种类型的助手:
template<class List, template<class> class Func> struct ForEachImpl;
template<class ...Types, template<class ...> class List, template<class> class Func>
struct ForEachImpl<List<Types...>, Func>
{
using type = List<Func<Types>...>;
};
template<class List, template<class> class Func>
using ForEach = typename ForEachImpl<List, Func>::type;
验证:
static_assert(std::is_same_v<ForEach<AsTuple, std::add_pointer_t>, std::tuple<int*, double*, std::string*>>);
也看看Boost.MP11
图书馆。它具有与上述功能mp_transform
等效的元功能。ForEach
推荐阅读
- unity3d - 升级 Unity 项目后“无法加载符号 clCreateCommandQueueWithProperties”
- python - 拆分numpy数组
- geolocation - 在 Sap Fiori Client App 上检查假 gps
- javascript - 我想填充猫鼬模式
- sql-server - SSH 隧道与 Azure SQL 数据库(PAS 服务)
- javascript - React 存储数据以进行复杂处理
- javascript - javascript - 输入为空时隐藏结果
- python - Plotly:如何在直方图中同时显示正态分布和核密度估计?
- javascript - 为什么这段代码说 Type 'number' 不能分配给 type 'never'
- javascript - 电子自定义关闭、最大化和最大化不起作用