c++ Brigand
- Brigand 是什么?
Brigand 是一个专为 C++11/14/17 设计的编译时元编程库,核心目标是简化 C++ 编译期数据结构(如类型列表、值列表)的操作,提供了类似 STL 但面向编译时的算法和容器。它完全基于模板元编程实现,无运行时开销,所有操作都在编译阶段完成,常被用于需要编译期类型推导、类型筛选 / 转换、编译期计算的场景(如反射、序列化、编译器插件开发)。简单来说:STL 是运行时操作数据,Brigand 是编译时操作类型 / 常量。
2. Brigand 常见用法
Brigand 的核心是围绕「编译期列表」(类型列表 brigand::list、值列表 brigand::integral_list)提供算法。
Brigand 实现了 STL 风格的编译期算法,如遍历、反转、删除、拼接等。
brigand::size<List>:获取列表长度(编译期常量); brigand::reverse<List>:反转列表; brigand::append<List1, List2,...>:拼接多个编译期列表; brigand::remove<List,T>:移除列表中指定类型的所有实例; brigand::for_each<List>(Callable):遍历的编译期列表,Callable可调用对象(lambda / 函数对象),接收一个编译期占位符参数 tbrigand::push_back<List, T>向类型 / 值列表末尾添加元素的元函数,返回一个新的列表(原列表不变)
3.安装Brigand
- 从 GitHub 下载源码:https://github.com/edouarda/brigand
- 将
brigand目录放到项目包含路径中; - 直接
#include <brigand/brigand.hpp>即可使用
4.实例代码
#include "brigand/brigand.hpp" #include <string> #include <iostream> #include <vector> //定义函数对象:处理单个类型 struct PrintType { template <typename T> void operator()(brigand::type_<T>) { // typeid(T).name() 输出类型名(不同编译器格式可能不同) std::cout << "类型:" << typeid(T).name()<<std::endl; } }; int main() { // 1. 内置类型列表 using IntTypes = brigand::list<char, short, int, long>; // 2. 自定义类型 + 模板类型 struct User {}; struct Order {}; using BusinessTypes = brigand::list<User, Order, std::vector<int>>; //获取列表数量brigand::size<IntTypes>::value constexpr size_t list1_size = brigand::size<IntTypes>::value; std::cout << "=== 列表长度输出 ===" << std::endl; std::cout<<"list_size:"<<list1_size<<std::endl; //遍历BusinessTypes并打印 std::cout << "=== 遍历BusinessTypes输出 ===" << std::endl; brigand::for_each<BusinessTypes>(PrintType()); //反转列表 using ReversedList1 = brigand::reverse<IntTypes>; std::cout << "=== 反转IntTypes输出 ===" << std::endl; brigand::for_each<ReversedList1>(PrintType()); //删除指定类型long using afterList = brigand::remove<IntTypes,long>; std::cout << "=== 删除IntTypes列表里的long输出 ===" << std::endl; brigand::for_each<afterList>(PrintType()); //拼接列表 using appedlist = brigand::append<BusinessTypes,IntTypes>; std::cout << "=== 拼接列表输出 ===" << std::endl; brigand::for_each<appedlist>(PrintType()); }
打印输出
=== 列表长度输出 === list_size:4 === 遍历BusinessTypes输出 === 类型:Z4mainE4User 类型:Z4mainE5Order 类型:St6vectorIiSaIiEE === 反转IntTypes输出 === 类型:l 类型:i 类型:s 类型:c === 删除IntTypes列表里的long输出 === 类型:c 类型:s 类型:i === 拼接列表输出 === 类型:Z4mainE4User 类型:Z4mainE5Order 类型:St6vectorIiSaIiEE 类型:c 类型:s 类型:i 类型:l

浙公网安备 33010602011771号