在C ++中构建一个调用表到模板函数 [英] Building a call table to template functions in C++

查看:138
本文介绍了在C ++中构建一个调用表到模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板函数,其中template参数是一个整数。在我的程序中,我需要使用在运行时确定的小整数调用该函数。我手工制作一个表,例如:

I have a template function where the template parameter is an integer. In my program I need to call the function with a small integer that is determined at run time. By hand I can make a table, for example:

void (*f_table[3])(void) = {f<0>,f<1>,f<2>};

并使用

f_table[i]();

现在,问题是如果有一些自动的方式来建立这个表的任意顺序。我可以想出的最好的是使用一个宏

Now, the question is if there is some automatic way to build this table to arbitrary order. The best I can come up with is to use a macro

#define TEMPLATE_TAB(n) {n<0>,n<1>,n<2>}

这至少避免了重复的函数名称实数函数的名称比f长)。然而,最大允许顺序仍然是硬编码的。理想情况下,表大小只能由代码中的一个参数决定。是否可以使用模板解决这个问题?

which at leasts avoids repeating the function name over and over (my real functions have longer names than "f"). However, the maximum allowed order is still hard coded. Ideally the table size should only be determined by a single parameter in the code. Would it be possible to solve this problem using templates?

推荐答案

您可以创建一个使用递归初始化查找表的模板;那么可以通过查找表中的函数来调用第i个函数:

You can create a template that initializes a lookup table by using recursion; then you can call the i-th function by looking up the function in the table:

#include <iostream>

// recursive template function to fill up dispatch table
template< int i > bool dispatch_init( fpointer* pTable ) {
  pTable[ i ] = &function<i>;
  return dispatch_init< i - 1 >( pTable );
}

// edge case of recursion
template<> bool dispatch_init<-1>() { return true; }

// call the recursive function
const bool initialized = dispatch_init< _countof(ftable) >( ftable );


// the template function to be dispatched
template< int i > void function() { std::cout << i; }


// dispatch functionality: a table and a function
typedef void (*fpointer)();    
fpointer ftable[100];

void dispatch( int i ){ return (ftable[i])(); }


int main() {
  dispatch( 10 );
}

这篇关于在C ++中构建一个调用表到模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆