c++ - template function to a function pointer inside a struct -


i wanted use template function(s) referencing via pointer using function pointer available inside structure like

typedef struct arithmeticfunc {           string funcname;           int (*funptr)(int,int); }; 

for example:

int add(int a, int b)     return (a+b);  int sub(int a, int b)     return (a-b);  arithmeticfunc func[2] = { {"addition", &add},                            {"subtract", &sub} };  for(int = 0; < 2; i++) {     printf("result of function : %s %d",func[i].funcname.c_str(),func[i]->funcptr(2,1)); } 

now need use template function instead of normal static function.

kindly let me know, doing on right method.

if understand question, want struct , functions templates?

template <typename t> struct arithmeticfunc {     std::string funcname;     t (*funptr)(t, t); };  template <typename t> t add(t a, t b) {     return a+b; }  template <typename t> t sub(t a, t b) {     return a-b; } 

then use them follows

int main() {     arithmeticfunc<int> func[2] = { {"addition", &add},                                     {"subtract", &sub} };      for(int = 0; < 2; i++)     {         std::cout << "result of function : "                    << func[i].funcname                   << " "                   << func[i].funptr(2,1)                   << std::endl;     } } 

note can no longer use %d format code if using templates, because type of t might not integer, may double, etc.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -