如果我有一个类需要使用类方法作为参数来调用父类方法,我可以使用 std::function
+ std::bind
如下图:
class A {
void complexMethod(std::function<void()> variableMethod) {
// other stuff ...
variableMethod();
// some other stuff..
}
}
class B : public A {
void myWay() {
// this and that
}
void otherWay() {
// other and different
}
void doingSomething() {
// Preparing to do something complex.
complexMethod(std::bind(&B::myWay, this));
}
void doingAnotherThing() {
// Different preparation to do some other complex thing.
complexMethod(std::bind(&B::otherWay, this));
}
}
我需要如何更改上述代码才能使用模板而不是 std::function
+ std::bind
实现相同的功能?
用 lambda 代替 std::function
+ std::bind
怎么样?我仍然想调用 B:myWay()
和 B::otherWay()
但使用 lambda。我不想用 lambda 替换 B:myWay()
和 B::otherWay()
。
是否有任何实现技术(上述之一或其他)可以使 variableMethod
返回类型和参数显式化?我该怎么做呢?假设 variableMethod
的签名是:
bool variableMethod(int a, double b);
推荐使用哪种技术?为什么(速度、灵活性、易用性……)?
最佳答案
模板+lambda解决方案:
struct A
{
template <typename F>
void runA(F func)
{
cout << 1 << endl;
func();
cout << 3 << endl;
}
};
struct B : A
{
int number = 2;
void runnable() { cout << number << endl; }
void runB()
{
cout << 0 << endl;
runA([this]() { runnable(); });
cout << 4 << endl;
}
};
int main()
{
B variable;
variable.runB();
}
为了将函数作为模板参数,只需像上面那样采用该函数的模板类型即可。 lambdas可以用来代替绑定(bind)以使事情变得更容易(this
被传递到 lambda 捕获列表)。
明确声明参数:
void run_func(std::function<bool(int, double)> func)
{
bool b = func(10, 10.01);
}
std::function
允许您像上面一样定义争论和返回类型。
关于c++ - 如何将类方法作为参数传递给另一个函数并稍后调用它,最好使变量类方法签名显式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70731559/