从Typelist子集创建一个函数指针

时间:2013-03-19 17:13:02

标签: c++ templates variadic-templates typelist

我的Typelist实现与this one非常相似。如果你不知道什么是类型列表:简而言之,它的行为类似于使用嵌套元组的可变参数模板。您可以阅读有关他们的更多信息here

我想从此类型列表的子集构建函数指针类型。子集由索引列表(任意大小)定义,并且所需操作在类型列表中查找这些索引,并使用这些类型作为参数定义函数上的指针类型。

API看起来像:

#include "typelist.h"
// typelist definition
typedef Typelist<float, Typelist<double, Typelist<int, NullType>>> Pixel;

typedef FunctionFromFields<Pixel, 0, 2>::Type field_0_and_2;
// I want the definition above to be equivalent to:
// typedef void (*field_0_and_2)(float*, int*);

假设这是可能的似乎是合理的,因为在编译时一切都是已知的,但我还没有找到正确的语法。

我不想使用可变参数模板来替换类型列表,但是它们可以用于定义指针类型。

有没有人做过类似的事情?

1 个答案:

答案 0 :(得分:2)

这应该相当容易。首先定义typelist_nth类型函数(左边作为练习;我假设你的typelist.h中有一个):

template<typename TL, int I> struct typelist_nth;

然后使用可变参数模板构建函数类型:

template<typename TL, int... Is> struct FunctionFromFields {
    typedef void (*Type)(typename typelist_nth<TL, Is>::type *...);
};
相关问题