使用函数模板初始化函数数组

时间:2012-04-23 01:06:52

标签: c++ template-meta-programming

我目前正在尝试使用模板元编程实现以下功能

typedef void (*function)(void*);
function function_array[/* total size of type list */];

...

template<typename T>
void some_func(void*)
{
    // do something with type T
}

...

function_array[0] = &some_func<type_0>;
function_array[1] = &some_func<type_1>;
function_array[2] = &some_func<type_2>;

...

function_array[n] = &some_func<type_n>;

我的目的是为类型的整数索引实现类型的动态调度机制。

似乎可以通过使用可变参数模板机制(C++/C++11 - Switch statement for variadic templates?)来实现,但目前我无法使用支持可变参数模板的编译器。

所以我试图通过使用类型列表(在现代C ++设计中)和模板递归作为下面的概念代码来解决。

template<typename list, typename function>
struct type_dispatch
{
    type_dispatch() { init(); }

    template<typename typelist>
    void init();

    template<typename head, typename tail>
    void init(cell<head, tail>&)
    {
        // setting dispatch array with templated function
        function_array[index_of<list, head>::value] = &function<head>;
        init(tail());
    }
    void init(null&) {}

    // functor array which size is equal to the size of type list    
    function function_array[size_of<list>::value];
};

当然,上面的代码将无法正确编译。我该如何实现此功能?

1 个答案:

答案 0 :(得分:1)

你的代码,修复了一些错误,填写了缺失的部分,编译对我来说很好:

struct null {};

template <typename head, typename tail>
struct cell {};

template <typename, typename>
struct index_of;

template <typename head, typename tail>
struct index_of<cell<head, tail>, head>
{
    static const int value = 0;
};

template <typename head, typename tail, typename other>
struct index_of<cell<head, tail>, other>
{
    static const int value = 1 + index_of<tail, other>::value;
};

template <typename>
struct size_of;

template <>
struct size_of<null>
{
    static const int value = 0;
};

template <typename head, typename tail>
struct size_of<cell<head, tail> >
{
    static const int value = 1 + size_of<tail>::value;
};

template <typename T>
void the_function(void*)
{
}

template<typename list, typename function_t>
struct type_dispatch
{
    type_dispatch() { init(list()); }

    template<typename head, typename tail>
    void init(cell<head, tail>)
    {
        // setting dispatch array with templated function
        function_array[index_of<list, head>::value] = &the_function<head>;
        init(tail());
    }

    void init(null) {}

    // functor array which size is equal to the size of type list    
    function_t function_array[size_of<list>::value];
};

typedef void (*function_t)(void*);

int main()
{
    type_dispatch<cell<int, cell<float, cell<double, null> > >, function_t> t;
}