How can I pass a function along with its signature (haskell style) using a C ++ template?

as a programming exercise, i decided to try and implement all of my haskell assignments for a course i am doing in c ++. I am currently 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 am getting the error:

macros.cc: In functionint main()’:
macros.cc:45:29: error: no matching function for call tocallfunc(int (&)())
      

what gives? I can send a function as an argument in exactly the same way, just without templates ... the only thing to change is to replace the type names in their correct places before compiling, no?

+3


source to share


1 answer


I think "void" is a "special case" in C ++. the compiler cannot match f () to f (void) replace it with some other type and compile. For me this is 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);
}

      

+1


source







All Articles