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 ステートメント? ) を使用することで実現できるようですが、現在、可変個引数テンプレートをサポートするコンパイラを使用できません。

そのため、型リスト (最新の 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 に答える