You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boost Mp11:如何检查映射中所有值是否属于指定列表?

检查Boost.MP11 Map中所有值是否属于指定List

针对你给出的元列表定义:

using List
    = boost::mp11::mp_list<EntityType, Name, Input, Position, Velocity,
                           Rotation, AnimationState, Interaction>;

using Map = boost::mp11::mp_list<
    boost::mp11::mp_list<Input, Input, Position, Velocity, Rotation>,
    boost::mp11::mp_list<AnimationState, AnimationState>>;

可以通过以下步骤实现编译时检查:

核心思路

  1. 对Map中的每个子列表,提取值部分(即子列表中除第一个元素外的所有元素,第一个元素视为键)
  2. 检查该值部分的所有元素是否都存在于List中
  3. 验证Map中所有子列表都满足上述条件

具体实现代码

#include <boost/mp11/mp_list.hpp>
#include <boost/mp11/mp_all_of.hpp>
#include <boost/mp11/mp_contains.hpp>
#include <boost/mp11/mp_rest.hpp>

// 预定义类型占位
struct EntityType {};
struct Name {};
struct Input {};
struct Position {};
struct Velocity {};
struct Rotation {};
struct AnimationState {};
struct Interaction {};

using List
    = boost::mp11::mp_list<EntityType, Name, Input, Position, Velocity,
                           Rotation, AnimationState, Interaction>;

using Map = boost::mp11::mp_list<
    boost::mp11::mp_list<Input, Input, Position, Velocity, Rotation>,
    boost::mp11::mp_list<AnimationState, AnimationState>>;

// 元谓词:检查单个子列表的所有值是否都在List中
template<typename SubList>
struct AllValuesAreInList : boost::mp11::mp_all_of<
    boost::mp11::mp_rest<SubList>, // 提取子列表的所有值(除第一个元素)
    boost::mp11::mp_contains<List, boost::mp11::_> // 检查元素是否在List中
> {};

// 最终检查:Map中所有子列表的值都符合要求
using AllMapValuesValid = boost::mp11::mp_all_of<Map, AllValuesAreInList<boost::mp11::_>>;

// 编译时验证
static_assert(AllMapValuesValid::value, "Map中存在不属于List的值");

代码说明

  • mp_rest<SubList>:获取子列表中除第一个元素外的所有元素,也就是需要检查的值集合
  • mp_contains<List, T>:判断类型T是否存在于List中,返回std::bool_constant
  • mp_all_of<Seq, Pred>:检查序列Seq中的所有元素是否都满足谓词Pred
  • AllValuesAreInList:自定义元谓词,封装对单个子列表的值检查逻辑
  • AllMapValuesValid:最终的检查结果,通过static_assert可以在编译时验证是否符合要求

如果Map中存在某个值不在List中,比如把其中一个值换成NonExistentType,static_assert会触发编译错误,提示不符合要求。

内容的提问来源于stack exchange,提问作者Archduke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:45:14