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
實例(即本身)到調用bind函數。因爲我想直接發送該實例,因爲它與調用對象相同。
如何以這種方式進行綁定?
即它必須返回相同的結果調用:
std::cout << "value: " << voice1.mTargetFunction(10.0) << std::endl;
std::cout << "value: " << voice2.mTargetFunction(100.0) << std::endl;
在'Voice'上提供一個調用'mTargetFunction(* this,whatever);'的方法。然後把它叫做'voice1.callTarget(10.0);' –
請注意,當你綁定時你會創建兩個'osc'對象。 – Slava
@Slava:你是什麼意思「你製作2份osc」? – markzzz