具有指向成员函数的指针的模板
Template with pointer to member function
我正在尝试为函数对象编写一个模板,以充当 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);
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址