假设我在一个类中有这个公共方法:
uli returnSum()
{
for_each(i, j, doSum);
return this->sum;
}void doSum(short int y)是同一个类的私有方法。我如何将其作为参数传递给for_each?
使用上面的语法,我得到了error: must use .* or ->* to call pointer-to-member function in __f (...)'。this->*doSum也不起作用。
我读过一些关于创建指向该成员函数的指针并将其作为参数传递的内容,但我不太确定如何做到这一点。
发布于 2013-02-07 04:50:12
您可以使用std::bind,如下所示
std::for_each(i, j, std::bind(&MyClass::doSum, this));发布于 2013-02-07 05:03:10
看一下下面的例子:
#include <iostream>
using namespace std;
class Test {
public:
int fun1(int x) { return x+1; }
};
typedef int (Test::*PtrType)(int);
void call(Test& self, PtrType prt) {
cout << (self.*ptr)(2) << endl;
}
int main() {
Test t;
call(t, &Test::fun1);
return 0;
}typedef int (Test::*PtrType)(int);这一行为类方法定义了类型的简单名称。(Test::*PtrType)周围的圆括号很重要;PtrType是新定义的类型(尽管您可以不使用call,并将整个签名放在call函数参数中,但强烈建议您使用这种方法)。
表达式(self.*ptr)(2)调用指针ptr所指向的方法,并将2作为其参数传递。同样,关键点是用括号将(self.*ptr)括起来。
最后要记住的一点是,在设置指针的值(&Test::fun1)时不能跳过&,即使使用常规函数也可以。
如果你使用模板,你可以让你的代码更整洁一些:
template <typename PtrT>
void call(Test& self, PtrT ptr) {
cout << (self.*ptr)(2) << endl;
}在这种情况下,不需要typedef,但是,您仍然必须记住调用中的括号。
如果您正在使用新的C++0x标准进行编译,则可以使用std::function或std::bind。
https://stackoverflow.com/questions/14738436
复制相似问题