c++ - 如何将类方法作为参数传递给另一个函数并稍后调用它,最好使变量类方法签名显式?

标签 c++ templates lambda

如果我有一个类需要使用类方法作为参数来调用父类方法,我可以使用 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/

相关文章:

c++ - 如何合并/更新 boost::property_tree::ptree?

c++ - 为什么在超出容量时 resize() 会导致 vector 内容的复制而不是 move ?

c++ - 如何让编译器推断出 C++11 中模板化方法的返回类型?

c++ - 模板中类的构造函数

java - 使用带有连接字符分隔符的收集器

c++ - 关于 lambda、函数指针的转换和私有(private)数据成员的可见性

c++ - 具有纯虚方法的抽象类 - 为什么可以执行 "Abstract * abs3;"?

c++ - Visual C++ 从 C++ 引用 C 函数

C++:有没有办法定义一个静态数组内联?

java - 在封闭范围内定义的局部变量 log 必须是最终的或有效最终的