加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在编译时建立和访问类型列表

发布时间:2020-12-16 03:25:17 所属栏目:百科 来源:网络整理
导读:我试图用c模板元编程来实现以下.我希望建立一个类型列表,然后一起收集这些类型,并在列表中进一步编译时处理.例如: foo.h中: class Foo { ... };// INSERT ANY CODE HERE bar.h: class Bar { ... };// INSERT ANY CODE HERE main.h: #include "foo.h"#inc
我试图用c模板元编程来实现以下.我希望建立一个类型列表,然后一起收集这些类型,并在列表中进一步编译时处理.例如:

foo.h中:

class Foo { ... };
// INSERT ANY CODE HERE

bar.h:

class Bar { ... };
// INSERT ANY CODE HERE

main.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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读