Template instantiation and function selection at runtime

*爱你&永不变心* 提交于 2019-12-06 01:34:54

You can't take pointers to function templates, because they are not functions, but need to be instantiated before. You can get a pointer like this:

typedef void (*Tfkt_int_int)( int, int );
Tfkt_int_int Ptr = &foo<int,int>;

As you can see, you need to specify possible combinations of types.

If there is many, and you want cleaner code, you can put all functions that share the same signature into one map. (That is, you need one map per signature.) Then distinguish which map to use in a switch statement.

std::map<char, Tfkt_int_int> Map_int_int;
Map_int_int['a'] = &foo<int,int>;
Map_int_int['b'] = &bar<int,int>;
// more ...

typdef void (*Tfkt_int_double)( int, double );
std::map<char, Tfkt_int_double> Map_int_double;
Map_int_double['a'] = &foo<int,double>;
Map_int_double['b'] = &bar<int,double>;
// more ...

If you want only one map, and are willing to sacrifice some of type savety, you can cast around the parameter types. It might be not as much of a loss in you situation, since you read that data from a byte stream already.

template <class T1, class T2> void foo(char* param1, char* param2)
{
  T1 P1 = *(reinterpret_cast<T1*>( param1 ));
  T2 P2 = *(reinterpret_cast<T2*>( param2 ));
  // ...
};

typedef void (*Tfkt)( char*, char* );
std::map<char, Tfkt> Map;
Map['a'] = &foo<int,int>;
Map['b'] = &foo<int,double>;
// more ...

Then call as:

double d;
int i;
char c = 'b';
(*(Map[c]))( reinterpret_cast<char*>(&i), reinterpret_cast<char*>(&d) );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!