gpt4 book ai didi

c++ - 使用函数模板初始化函数数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:32:35 24 4
gpt4 key购买 nike

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

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

当然,上面的代码不会被正确编译。如何实现此功能?

最佳答案

您的代码在修复了一些错误并填充了缺失的部分后,对我来说编译得很好:

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

关于c++ - 使用函数模板初始化函数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10273642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com