gpt4 book ai didi

c++ - 回调中的仿函数 : compilation errors

转载 作者:搜寻专家 更新时间:2023-10-31 01:55:04 25 4
gpt4 key购买 nike

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

这是代码

#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 也是如此

最佳答案

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

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

关于c++ - 回调中的仿函数 : compilation errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8833822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com