1

I'm not sure how to phrase this question. I have a simple demo.

I thought this code would work but I get the compile errors below. Changing T to int (the commented out line) makes it work but now it no longer is generic. Why isn't this current version compiling? and how do I make this work?

#include <cstdio>
#include <functional>
template<class T>
void test(T t, std::function<void(T)> f) { f(t); }
//void test(T t, std::function<void(int)> f) { f(t); }

void PrintIt(int v){ printf("V=%d\n", v); };


int main(int argc, char *argv[]) {
    test(5, PrintIt);
}

Results:

prog.cpp: In function 'int main(int, char**)':
prog.cpp:11:20: error: no matching function for call to 'test(int, void (&)(int))'
     test(5, PrintIt);
                    ^
prog.cpp:11:20: note: candidate is:
prog.cpp:4:6: note: template<class T> void test(T, std::function<void(T)>)
 void test(T t, std::function<void(T)> f) { f(t); }
      ^
prog.cpp:4:6: note:   template argument deduction/substitution failed:
prog.cpp:11:20: note:   mismatched types 'std::function<void(T)>' and 'void (*)(int)'
     test(5, PrintIt);
  • 2
    Well, you could use the `typename identity::type` trick to make the compiler not use the second parameter for deduction. – chris Jun 21 '15 at 06:25
  • 1
    @chris Or just `template void test(T t, F f)` and avoid the type erasure entirely. – T.C. Jun 21 '15 at 06:26
  • @T.C., Much better assuming it's preferable over `std::function` in the actual code. – chris Jun 21 '15 at 06:27

0 Answers0