Passing functor and function pointers interchangeably using a templated method in C++
- by metroxylon
I currently have a templated class, with a templated method. Works great with functors, but having trouble compiling for functions.
Foo.h
template <typename T>
class Foo {
public:
// Constructor, destructor, etc...
template <typename Func>
void bar(T x, Func f);
};
template <typename T>
template <typename Func>
Foo::bar(T x, Func f) { /* some code here */ }
Main.cpp
#include "Foo.h"
template <typename T>
class Functor {
public:
Functor() {}
void operator()(T x) { /* ... */ }
private:
/* some attributes here */
};
void Function(T x) { /* ... */ }
int main() {
Foo<int> foo;
foo.bar(2, Functor); // No problem
foo.bar(2, Function); // <unresolved overloaded function type>
return 0;
}