C++ C++;函子重载typedef到函数指针
我有以下代码: Typedef到函数指针C++ C++;函子重载typedef到函数指针,c++,overloading,function-pointers,objective-c++,functor,C++,Overloading,Function Pointers,Objective C++,Functor,我有以下代码: Typedef到函数指针 typedef bool(*tMyFunc)(tSomeTypeDef); class MyOtherClass { MyClass* m_instance; public: bool operator ()(tSomeTypeDef val); } MyOtherClass::MyOtherClass() { //... init m_instance, then register callback as follows
typedef bool(*tMyFunc)(tSomeTypeDef);
class MyOtherClass {
MyClass* m_instance;
public:
bool operator ()(tSomeTypeDef val);
}
MyOtherClass::MyOtherClass()
{
//... init m_instance, then register callback as follows
[m_instance registerNotificationWithCallback:*this];
}
bool MyOtherClass::operator ()(tSomeTypeDef val)
{
return false;
}
函数指针用于声明成员变量,以指向Obj-C类中的回调函数
@interface MyClass : NSObject
{
tSomeTypeDef _someValue;
tMyFunc _callback;
}
- (void) registerNotificationWithCallback:(tMyFunc)callback;
@end
@implementation MyClass
- (void) registerNotificationWithCallback:(tMyFunc)callback {
_callback = callback;
}
- (void) didSomething:(NSNotification*)notification {
if (_callback)
_callback(_someValue);
}
@end
在C++类中,我想传递一个函子代替TMyFUNC函数指针
typedef bool(*tMyFunc)(tSomeTypeDef);
class MyOtherClass {
MyClass* m_instance;
public:
bool operator ()(tSomeTypeDef val);
}
MyOtherClass::MyOtherClass()
{
//... init m_instance, then register callback as follows
[m_instance registerNotificationWithCallback:*this];
}
bool MyOtherClass::operator ()(tSomeTypeDef val)
{
return false;
}
它编译时带有错误
没有从“MyOtherClass”到“tMyFunc”(又名“bool(*)(tSomeTypeDef))的可行转换是的,这是正确的。函数指针的语义比函数对象更受限制。你想用函数对象而不是函数指针来实现你的类。@DietmarKühl-hmm,我不想用std::function来“typedef”一个函子,我不能在我的构建中包含stdlib,我没有说任何关于
std::function
的内容,尽管这是你遇到的问题的解决方案。然而,是的,我的观点是,如果您不想被限制使用函数指针,您需要使用类型擦除的函数对象。不过,编写一个自定义版本的std::function
并不难。@DietmarKühl当然可以,谢谢。