2

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

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];
};

当然,上面的代码不会被正确编译。我怎样才能实现这个功能?

4

1 回答 1

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;
}
于 2012-04-23T01:46:28.917 回答