I am trying to use a template that takes in an std::function, but the template argument deduction is failing.
double foo(){
return 2.3;
}
template <typename V>
void funcC (V (*fptr)()){
std::cout << "C function's value is\"" << fptr() << '\"' << std::endl;
}
template <typename V>
void funcCxx (std::function<V()> fptr){
std::cout << "C++ function's value is\"" << fptr() << '\"' << std::endl;
}
funcC (foo);
funcCxx (foo);
The C function-pointer style (funcC) works, but the C++ std::function (funcCxx) doesn't.
I get this compiler error candidate template ignored: could not match 'function<type-parameter-0-0 ()>' against 'double (*)()'
Any idea what causes this error? Just in case, this is being compiled in clang with C++17, but I don't think it's a compiler error.
It cannot be deduced because you are not passing a std::function
to funcCxx
.
Function argument and parameter type must match in template argument deduction. Otherwise deduction fails.
You could let the function take any type instead of constraining it to function pointers or std::function
and then you can construct the std::function
inside the function:
template <typename V>
void funcCxx (V&& v){
auto f = std::function(std::forward<V>(v));
std::cout << "C++ function's value is\"" << f() << '\"' << std::endl;
}