【问题标题】:C++ std::bind Function as Parameter Store in Class VariableC++ std::bind 函数作为类变量中的参数存储
【发布时间】:2021-08-21 01:16:36
【问题描述】:

我有以下问题。 class A 实现了一些应在 B 类中处理的数据集上使用的例程。这意味着我正在从 class A 调用函数 start。我正在做的事情应该保存在class A 中的变量m 中。到目前为止,一切都很好。但是,当访问类变量m时,它仍然处于初始化时的状态。

准确地说:

#include <iostream>
#include <functional>

class A {
    public:
        int m;
        A() {
            m = 100;
        }
        void start(int value) {
            std::cout << "hello there!" << std::endl;
            m = value;
        }
};

class B {
    private:
        int m;
    public:
        void doSomething() {
            A a;
            doSomething2(std::bind(&A::start,a, std::placeholders::_1));
            
            // access variable m of instance a
            std::cout << a.m << std::endl;

        }
        template <typename Callable>
        void doSomething2(Callable f) {
            int val = 4444;
            f(val);
        }
};

main()
{
    B b;
    b.doSomething();
}

执行此操作时,我将得到100 作为m 的输出。我如何能够将调用 start 所做的更改存储在类变量中?意思是,像本例一样存储值4444?谢谢

【问题讨论】:

    标签: c++ function class std stdbind


    【解决方案1】:

    看起来您需要确保std::bind 使用的是指向您创建的实际类实例的指针。尝试将其更改为:

    // notice I've got '&a' here instead of just 'a'
    doSomething2(std::bind(&A::start, &a, std::placeholders::_1));
    

    如果没有这个,我猜bind 现在正在做的是复制a 实例,然后修改该实例而不是更改它。

    【讨论】:

      【解决方案2】:

      默认情况下,Bind 按值接受参数,结果start() 作用于对象a 的副本。您必须通过引用传递它:

      doSomething2(std::bind(&A::start, std::ref(a), std::placeholders::_1));
      

      可能的替代方法是使用 lambda 表达式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 2019-04-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多