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;发布于 2017-02-17 00:00:37
如果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;这里重要的一点是对Voice参数使用std::ref。
如果要调用的总是Modulate成员函数,则Voice构造函数不必将指向成员函数的指针作为参数,然后在对std::bind的调用中使用&T::Modulate。
https://stackoverflow.com/questions/42278563
复制相似问题