Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i pass a function along with its signature (haskell style) using a c++ template?

as a programming exercise, i've decided to try to implement all my haskell assignments for a course i'm doing in c++ as well. currently, i'm trying to send this function :

int callme(){
    cout << "callme called" << endl;
    return 0;
}

to this function:

template<class type1,class type2> void callfunc(type1(*f)(type2)){
    (*f)(); 
}

with this call:

int main(){
    callfunc<int,void>(callme);
}

but i get the error:

macros.cc: In function ‘int main()’:
macros.cc:45:29: error: no matching function for call to ‘callfunc(int (&)())’

what gives? i'm able to send a function as an argument in the exact same way, just without the templates...the only thing that should be changing is substituting the type names into their proper places before compilation, no?

like image 324
russell88 Avatar asked Nov 29 '25 02:11

russell88


1 Answers

I think 'void' is a 'special case' in c++. the compiler cannot match f() to f(void) replace it with any other type and it will compile. For me it's just another c++ magic, but maybe someone knows better. This will compile:

int callme(int){ printf("ok int\n"); return 0; }
int callme(char){ printf("ok char\n"); return 0; }
template<class type1,class type2> void callfunc(type1(*f)(type2), type2 p) {
  (*f)(p);
}

int main() {
  callfunc<int,int>(callme, 1);
  callfunc<int,char>(callme, 1);
}
like image 124
exebook Avatar answered Dec 01 '25 15:12

exebook