我正在做测试以了解 lambda。我试图向用户提供直接在主函数中重写函数的能力。让我解释一下:
#include <iostream>
using namespace std;
class A {
public:
virtual bool execute() {};
};
class B : public A {
public:
bool execute() { cout << "Execute in B" << endl; }
};
int main() {
B newB;
newB.execute();
newB.execute() { cout << "Execute in New B" << endl; } ;
newB.execute();
return 0;
}
此源代码不起作用,因为重写这样的函数是非法的。什么对你来说是重写像 C++14 中那样的函数的最佳方法?用 lambda ?没有 lambda?
我想像在 Javascript 中一样,重载这样的函数:newB.somefunction = function(...) { ... };。我希望该函数由我的图书馆的用户以源代码编写。在某种程度上是回调函数。
我的问题是:如何编写回调函数或 Lambda 表达式来重写类/对象外部的方法?
Exagon 提出的带有变量的解决方案:
#include <iostream>
#include <functional>
class B {
public:
int global=0;
std::function<void()> execute{
[](){
std::cout << "Hello World" << std::endl;
}
};
};
int main() {
B newB;
newB.execute();
newB.execute();
newB.execute = [newB](){std::cout << newB.global << " = FOOBAR\n";};
newB.execute();
return 0;
}
最佳答案
您可以使用 functional
header 中的 std::function
来执行此操作。
然后创建一个 std::function
成员并为这个成员创建一个 setter。
execute
成员函数需要调用此 std::function
成员。
您可以将 lambda 传递给 setter 方法。
这是我的方法:
#include <iostream>
#include <functional>
class B {
public:
void execute() {_f();}
void setFunction(std::function<void()> f){ _f = f;}
private:
std::function<void()> _f{[](){std::cout << "Hello World" << std::endl;}};
};
int main() {
B newB;
newB.execute();
newB.execute();
newB.setFunction([](){std::cout << "FOOBAR\n";});
newB.execute();
return 0;
}
输出是:
Hello World
Hello World
FOOBAR
因为你在追求“类似 JavaScript”的东西,你可以这样做:
#include <iostream>
#include <functional>
class B {
public:
std::function<void()> execute{
[](){
std::cout << "Hello World" << std::endl;
}
};
};
int main() {
B newB;
newB.execute();
newB.execute();
newB.execute = [](){std::cout << "FOOBAR\n";};
newB.execute();
return 0;
}
具有相同的输出。
here是现场演示
关于c++ - 建议用户用 lambda 重写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41925920/