mardi 25 octobre 2016

What's wrong my std::function wrapper template?

Why doesn't this work?

// File: functional.cpp
// I'm trying to make a function template for a function that returns
// the return type of a std::function that takes no arguments.
//
// If declared as follows, the code below won't compile.  
// If NOT templated, but rather defined as two separated functions,
// the code below works as expected.
template <class TT>
TT call_func(std::function<TT()> func) {
  return func();
}

int f1() { return 10; }
const char* f2() { return "Hello, World!"; }

int main(int argc, char**argv)
{
  std::cout << call_func(f1) << "\n";
  std::cout << call_func(f2) << "\n";
  return 0;
}

GCC errors:

functional.cpp: In function ‘int main(int, char**)’:
functional.cpp:19:28: error: no matching function for call to ‘call_func(int (&)())’
   std::cout << call_func(f1) << "\n";
                            ^
functional.cpp:5:4: note: candidate: template<class TT> TT call_func(std::function<TT()>)
 TT call_func(std::function<TT()> func) {
    ^
functional.cpp:5:4: note:   template argument deduction/substitution failed:
functional.cpp:19:28: note:   mismatched types ‘std::function<TT()>’ and ‘int (*)()’
   std::cout << call_func(f1) << "\n";

Aucun commentaire:

Enregistrer un commentaire