【问题标题】:Propose to the user to rewrite functions with lambda建议用户用 lambda 重写函数
【发布时间】:2017-01-29 21:01:31
【问题描述】:

我正在进行测试以了解 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?

我想在 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;
}

【问题讨论】:

  • 您希望库的用户以源代码编写函数吗?还是您希望应用程序的用户在运行时编写函数? ...对于后者,请检查ChaiScript
  • 你好 ChaiScript,我想在 Javascript 中做类似的事情,重载这样的函数:newB.somefunction = function(...) { ... };。我希望这个函数由我的库的用户用源代码编写,完全正确。
  • 听起来你想要某种形式的回调。更改您的类以接受 std::function&lt;&gt; int 他的构造函数,并在您调用 execute 时调用它。
  • 我不记得“回调”这个词了。谢谢
  • 你的用户是谁,你为什么要让他们写代码?你的产品是库还是编译器?

标签: c++ lambda c++14


【解决方案1】:

您可以使用 functional 标头中的 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 是现场演示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多