回调中的函子:编译错误

发布于 2024-12-26 03:35:08 字数 956 浏览 2 评论 0原文

我有一个使用回调的简单函数,我想使用函子而不是普通函数作为回调。但我收到编译错误。看来我错过了一些东西。

这是代码

#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 的情况相同

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哆兒滾 2025-01-02 03:35:08

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

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

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

template <class Functor>
void some_func( Functor f ) 
{
    f();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文