这是我的attempt
#include <iostream>
#include <functional>
class Voice;
class EnvelopeMultiPoints
{
public:
std::function<double(Voice &, double)> mCallback;
void SetupModulation(std::function<double(Voice &, double)> callback, int paramID) {
mCallback = callback;
}
};
class Voice
{
public:
EnvelopeMultiPoints mEnvelopeMultiPoints;
};
class VoiceManager
{
public:
Voice mVoices[16];
inline void UpdateVoices(std::function<void(Voice &)> callback) {
for (int i = 0; i < 16; i++) {
callback(mVoices[i]);
}
}
static void SetupEnvelopeMultiPointsModulation(Voice &voice, std::function<double(Voice &, double)> callback, int paramID) {
voice.mEnvelopeMultiPoints.SetupModulation(callback, paramID);
}
};
class Oscillator
{
public:
double ModulatePitch(Voice &voice, double currentValue) {
// somethings with voice
return currentValue * 10.0;
}
};
int main()
{
VoiceManager voiceManager;
Oscillator *pOscillator = new Oscillator();
int param = 100;
auto callback = std::bind(&Oscillator::ModulatePitch, pOscillator, std::placeholders::_1, std::placeholders::_2);
voiceManager.UpdateVoices(std::bind(&VoiceManager::SetupEnvelopeMultiPointsModulation, std::placeholders::_1, callback, param));
Voice voice = voiceManager.mVoices[0];
std::cout << voice.mEnvelopeMultiPoints.mCallback(voice, 1.0) << std::endl;
delete pOscillator;
}我创建了一种Voice Updater "basic“迭代器,稍后我可以传递任何类型的函数。它迭代所有的声音,并传递迭代所需的函数。
但是似乎我在绑定Oscillator::ModulatePitch函数来传递给更新器上是错误的?
我哪里错了?
发布于 2017-02-17 22:02:04
正如pergy在其评论中所写的那样,如果你使用std::function<double(Voice &, double)> callback = ...而不是auto,它就可以工作。原因是它强制从bind对象转换为std::function。
如果你这样做了
auto callback1 = std::bind(&Oscillator::ModulatePitch, pOscillator, std::placeholders::_1, std::placeholders::_2);
std::function<double(Voice &, double)>callback2 = std::bind(&Oscillator::ModulatePitch, pOscillator, std::placeholders::_1, std::placeholders::_2);
std::cout << typeid(callback1).name();
std::cout << typeid(callback2).name();你会发现返回的类型是不同的。在这种情况下,第二个bind尝试使用第二个类型构建它的对象(这不起作用)。我认为转换运算符(从bind到std::function)没有被外部bind调用存在问题。
https://stackoverflow.com/questions/42295189
复制相似问题