Passing functor and function pointers interchangeably using a templated method in C++

Posted by metroxylon on Stack Overflow See other posts from Stack Overflow or by metroxylon
Published on 2012-10-17T22:59:45Z Indexed on 2012/10/17 23:00 UTC
Read the original article Hit count: 190

Filed under:
|
|
|

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;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about function