具有指向成员函数的指针的模板

Template with pointer to member function

本文关键字:指针 函数 成员      更新时间:2023-10-16

我正在尝试为函数对象编写一个模板,以充当 STL 算法函数中的谓词。我对此还很陌生,我不能完全正确

这是模板:

#ifndef MEMBERPREDICATE_H
#define MEMBERPREDICATE_H
template <typename Type, typename Class>
class MemberPredicate{
public:
    MemberPredicate(Type (Class::*method)(), bool (*operation)(Type,Type), Type data) : method(method), operation(operation), data(data){};
    bool operator()(Class * other){ return *(this->operation)(other->*(this->method)(), this->data);}
private:
    Type (Class::*method)();
    bool (*operation)(Type,Type);
    Type data;
};
#endif

构造函数采用指向类的 (get) 方法的指针,指向作用于该 get 方法返回的值的比较运算符的指针,并最终确定一些它应该用于比较的数据

我尝试通过以下方式使用该模板:

bool equal(int a, int b){
    return a == b;
}
MemberPredicate<int, IntClass> pred(&IntClass::getInt, &equal, 4)
IntClass * i = new IntClass(5) // stores 5 in IntClass and returns this value when i->getInt() is called
pred(i);
当我

不使用函数对象的函数部分时,我可以很好地编译,但是当我尝试将其应用于i时,我收到一个错误:

Must use '.*' or '->*' to call pointer to member function in Member...
bool operator()(Class * other){ return *(this->operation)(other->*(this->method)(), this->data);}

这里的标记在箭头下方other->我尝试将箭头追逐到点并随机移动它们,但无法让它工作。

正如我所说,我对此很陌生,很可能这是一种非常奇怪的处理方式。 如果是这样的话,非常欢迎正确方向的指针,但我仍然想掌握这部分。

最后我有一个额外的问题,在我让这部分工作后,我会想让 get-method const 工作,但我不确定如何,这里的任何帮助也会很好。

谢谢

*(this->operation)(other->*(this->method)(), this->data);
^                         ^

由于运算符优先级,在取消引用函数指针之前调用调用运算符()。只有在调用调用运算符,才会取消引用它。

将其更改为:

(*this->operation)((other->*(this->method))(), this->data);
 ^                         ^

请注意,我还在other->*(this->method)() 周围放了另一对括号。这是必需的,因为(this->method)()other->*之前会进行评估。


此外,正如@dyp所说,您省略了大多数this限定符,从而产生结果:

operation((other->*method)(), data);