在编译时生成和访问类型列表
building and accessing a list of types at compile time
我正在尝试使用 c++ 模板元编程实现以下目标。我希望建立一个类型列表,然后将这些类型收集在一起,并对列表进行进一步的编译时处理。所以例如:
傅炯:
class Foo { ... };
// INSERT ANY CODE HERE
酒吧:
class Bar { ... };
// INSERT ANY CODE HERE
主.h:
#include "foo.h"
#include "bar.h"
struct list_of_types {
typedef /* INSERT ANY CODE HERE */ type;
};
我可以将任何代码插入上面的插槽中,只要 list_of_types::type 解析为包含 Foo 和 Bar 类型的列表的某种表示形式(例如 boost::mpl::vector)。以下限制适用:
foo.h 中的代码不应该知道 bar.h 中的代码,反之亦然。应该可以更改 main.h 中 #include 指令的顺序,而不更改任何其他代码。
如果我包含更多向列表中添加更多类型的标头,则 main.h 中的代码不必更改。
类型列表必须在编译时可用。我计划做涉及该列表的进一步元编程。
利用通用标头、可变参数模板和宏的解决方案:
// Header common.h
// A distinct Void type
struct Void {};
template <typename ...> struct concat;
template <template <typename ...> class List, typename T>
struct concat<List<Void>, T>
{
typedef List<T> type;
};
template <template <typename ...> class List, typename ...Types, typename T>
struct concat<List<Types...>, T>
{
typedef List<Types..., T> type;
};
template <typename...> struct TypeList {};
template <>
struct TypeList<Void> {};
typedef TypeList<Void> TypelistVoid;
#define TYPE_LIST TypelistVoid
// Header foo.h
#include <common.h>
class Foo { };
typedef typename concat<TYPE_LIST, Foo>::type TypeListFoo;
#undef TYPE_LIST
#define TYPE_LIST TypeListFoo
// Header bar.h
#include <common.h>
class Bar { };
typedef typename concat<TYPE_LIST, Bar>::type TypeListBar;
#undef TYPE_LIST
#define TYPE_LIST TypeListBar
// Header main.h
#include "foo.h"
#include "bar.h"
struct list_of_types {
typedef TYPE_LIST type;
};
// Or just typedef TYPE_LIST list_of_types;
// Test
#include <iostream>
#include <typeinfo>
template <template <typename ...> class List, typename T, typename ...Types>
void info();
template <typename T, typename ...Types>
inline void info(TypeList<T, Types...>) {
std::cout << typeid(T).name() << std::endl;
info(TypeList<Types...>());
}
template <typename T>
inline void info(TypeList<T>) {
std::cout << typeid(T).name() << std::endl;
}
int main() {
info(list_of_types::type());
return 0;
}
template <typename ... Types>
void info(TypeList<Types...>) {
std::initializer_list<std::string> ls { typeid(Types).name() ... };
for (auto& name : ls)
std::cout << name << std::endl;
}
int main() {
info(TYPE_LIST());
return 0;
}
相关文章:
- 使用简单类型列表实现的指数编译时间.为什么
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- 测试两个类型列表中的所有组合
- 谷歌测试:模板模板的笛卡尔乘积的类型列表与模板
- 在迭代模板类型列表时无法停止递归
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- c++ 循环访问对象列表并删除对象
- 阅读从 istream 到矢量的不同类型列表
- 循环访问对象列表 c++
- 如何在C++中创建类型列表的 n 路笛卡尔积?
- c++17通过生成预先声明的类型列表的笛卡尔乘积来生成std::变体
- 将变量模板限制为类型列表
- 我可以使用特征指定变体的类型列表吗?
- 如何对要用于模板参数的类型列表进行编码
- 创建类型列表并访问每种类型的静态成员?
- 为什么BOOST :: HANA :: EXAREMIS ::键入实验功能?类型列表的棘手是什么
- 如果创建支持返回可变参数类型列表的通用模板 API,我应该使用 std::tuple 还是其他东西?
- 能够访问逐项列表的最佳结构
- 在编译时生成和访问类型列表
- 在 c++ 中访问类中的字段和类型列表