2

I have a simple function that uses a callback and I want use functor instead of normal function to be used as callback. But I get compilation error. It seems I missing smth.

Here is the code

#include <iostream>
#include <functional>

void some_func( void (*f)() ) 
{
    f(); 
}

class Functor
{
public:
    void g() { std::cout << "world"; }
    void operator() () { std::cout << "hello"; }
};

void g()
{
    std::cout << "beautiful";
}

int main(int c, char**v)
{
    Functor f;
    f();
    some_func(g);
    some_func(f);//line 26
    some_func(std::bind(&Functor::g, f));//line 27
    return 0;
}

Results:

g++ 1.cpp std=c++0x
1.cpp: In function 'int main(int, char**)':
1.cpp:26:16: error: cannot convert 'Functor' to 'void (*)()' for argument '1' to 'void some_func(void (*)())'
1.cpp:27:37: error: cannot convert 'std::_Bind<std::_Mem_fn<void (Functor::*)()>(Functor)>' to 'void (*)()' for argument '1' to 'void some_func(void (*)())'

Same story for cl

Lol4t0
  • 12,444
  • 4
  • 29
  • 65

1 Answers1

3

some_func takes only real function pointers as arguments, not functor classes. Try using:

template <class Functor>
void some_func( Functor f ) 
{
    f();
}
thiton
  • 35,651
  • 4
  • 70
  • 100
  • I see. What should I do with `some_func` to take functors & what is the difference with this http://stackoverflow.com/questions/8819580/callback-function-pointers-c-with-without-classes , where `setTimer` _can_ accept functors? – Lol4t0 Jan 12 '12 at 10:57
  • @Lol4t0: Whether `setTimer` can accept functors is doubtful in the question you linked. See the comments to the aspected answer. – thiton Jan 12 '12 at 11:00
  • Oh, I just saw that answer is accepted. Ok, than it's all clear – Lol4t0 Jan 12 '12 at 11:02
  • And one note also, I hadn't to rewrite `some_func(g);` – Lol4t0 Jan 12 '12 at 11:08