c++ - 建议用户用 lambda 重写函数

标签 c++ lambda c++14

我正在做测试以了解 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/

相关文章:

c++ - 自定义 std::set 比较器 - 不匹配调用 [...]

c++ - 如何使用 Eigen for B-Splines 处理噪声序列数据

c++ - 用于存储自定义对象/数据类型的通用 B 树

C++ lambda 通过引用捕获上下文以及 `this` 指针

C#:使用 Linq 和 Lambda 获取 2 个集合之间不匹配的元素

c++ - 如何让 C++ ADL 查看模板的所有实例?

c++ - 使用 unique_ptr 成员编写移动构造函数的正确方法(崩溃)

c++ - 使用 boost.test 时如何让 std::cout 显示在 eclipse IDE 控制台中?

c++ - 模板中的第二个lambda函数导致编译错误(智能感知无法检测到问题)-错误C2988

c++ - 无法使用 lambda 函数创建 unordered_set