I have stumbled upon an issue with templates in clang++
that I do not know how to solve.
I wish to use templated functions that take a class and a function as arguments. But when the function is an overloaded function, I get the error candidate template ignored: couldn't infer template argument 'F'
which is totally sensible.
For instance, the example program
#include <iostream>
#include <math.h>
template<class T, typename F>
T foo(F f,T x){
return f(x);
}
int main(void) {
std::cout << "foo(sinf,0.34) is " << foo(sinf,0.34) << std::endl;
return 0;
}
works exactly as I want. Now, if I use an overloaded function such as sin
instead of sinf
, the template argument cannot be inferred. How can I change the function template of foo
to help the compiler resolving the type of F
?
You can use a lambda to solve the ambiguity with overloads, eg:
foo([](double d){ return sin(d); }, 0.34)
On a side note, in C++, you should use <cmath>
instead of <math.h>
directly. You can use using namespace std;
or better using std::sin;
to bring std::sin
into the calling namespace if you don't want to qualify it at the call site.