Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overloaded Function as Argument to Templated Function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading