【问题标题】:Functor in callback: compilation errors回调中的函子:编译错误
【发布时间】:2012-01-12 10:50:12
【问题描述】:

我有一个使用回调的简单函数,我想使用仿函数而不是普通函数作为回调。但我得到编译错误。看来我错过了什么。

这里是代码

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

结果:

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 (*)())'

cl 也是如此

【问题讨论】:

  • Functor::operator()()的类型不是void (*)();我想是void (Functor::*)()
  • 这似乎无关紧要。我将Functor 传递给some_func,而不是Functor::operator ()
  • @Lol4t0:不过,它的方向是正确的,因为Functor 也不是void(*)()
  • 我以为operator ()的存在让我把Functor转换成void(*)(),别问我为什么

标签: c++ function-pointers


【解决方案1】:

some_func 只接受真正的函数指针作为参数,而不是仿函数类。尝试使用:

template <class Functor>
void some_func( Functor f ) 
{
    f();
}

【讨论】:

  • 我明白了。我应该如何处理 some_func 来获取函子?这与 stackoverflow.com/questions/8819580/… 有什么区别,setTimer 可以接受函子?
  • @Lol4t0:setTimer 是否可以接受函子在您链接的问题中是值得怀疑的。请参阅相关答案的 cmets。
  • 哦,我刚刚看到这个答案被接受了。好的,比这一切都清楚
  • 还有一个注释,我不必重写some_func(g);
猜你喜欢
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
相关资源
最近更新 更多