【问题标题】:Create a function pointer from Typelist subsets从 Typelist 子集创建函数指针
【发布时间】:2013-03-19 17:13:01
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c++ templates variadic-templates typelist


    【解决方案1】:

    这应该很容易。首先定义一个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 *...);
    };
    

    【讨论】:

    • 是的,做到了。确实不难,我只是对语法感到困惑。
    猜你喜欢
    • 2016-09-30
    • 2017-02-04
    • 2023-03-12
    • 2023-03-22
    • 2011-02-21
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多