我怎样才能自动发送" bind函数中调用对象的实例?

时间:2017-02-16 15:47:32

标签: c++ bind

Here's my code

#include <iostream>
#include <functional>
#include <vector>

class Voice
{
public:
    double mVoiceValue = 0.0;
    std::function<double(Voice &, double)> mTargetFunction;

    Voice(std::function<double(Voice &, double)> targetFunction) : mTargetFunction(targetFunction) { }
    ~Voice() { }    

private:
};

class Osc
{
public:
    double mOscValue = 1.0;

    Osc() { }
    ~Osc() { }

    double Modulate(Voice &voice, double value) {
        return mOscValue * voice.mVoiceValue * value;
    }

private:
};

int main()
{
    Osc *osc = new Osc();
    Voice voice1(std::bind(&Osc::Modulate, osc, std::placeholders::_1, std::placeholders::_2));
    Voice voice2(std::bind(&Osc::Modulate, osc, std::placeholders::_1, std::placeholders::_2));

    voice1.mVoiceValue = 1.0;
    voice2.mVoiceValue = 2.0;
    std::cout << "value: " << voice1.mTargetFunction(voice1, 10.0) << std::endl;
    std::cout << "value: " << voice2.mTargetFunction(voice2, 100.0) << std::endl;
}

我希望不将voice1 / voice2实例(即自身)传递给调用绑定函数。因为我想直接发送该实例,因为它与调用对象相同。

我怎么能以这种方式绑定?

即。它必须返回相同的结果调用:

std::cout << "value: " << voice1.mTargetFunction(10.0) << std::endl;
std::cout << "value: " << voice2.mTargetFunction(100.0) << std::endl;

1 个答案:

答案 0 :(得分:0)

如果Voice构造函数可以使用两个参数(Osc对象和成员函数指针),你可以解决这个问题:

class Voice
{
public:
    double mVoiceValue = 0.0;
    std::function<double(double)> mTargetFunction;

    template<typename T, typename F>
    Voice(T& targetObject, F&& targetFunction)
        : mTargetFunction(std::bind(targetFunction, targetObject, std::ref(*this), std::placeholders::_1)) { }
    ~Voice() { }
};

class Osc
{
public:
    double mOscValue = 1.0;

    Osc() { }
    ~Osc() { }

    double Modulate(Voice &voice, double value) {
        return mOscValue * voice.mVoiceValue * value;
    }
};

...

Osc   osc;
Voice voice1(osc, &Osc::Modulate);
Voice voice2(osc, &Osc::Modulate);

voice1.mVoiceValue = 1.0;
voice2.mVoiceValue = 2.0;
std::cout << "value: " << voice1.mTargetFunction(10.0) << std::endl;
std::cout << "value: " << voice2.mTargetFunction(100.0) << std::endl;

这里重要的一点是对std::ref参数使用Voice

如果始终是要调用的Modulate成员函数,则Voice构造函数不必将指向成员函数的指针作为参数,然后使用{{ 1}}调用&T::Modulate