2017-02-17 58 views
0

這是我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; 
} 

我創造一種語音更新「基本」的迭代器,我可以通過以後任何種類的功能。它迭代所有的聲音並傳遞我需要的迭代函數。

但似乎我錯了綁定Oscillator::ModulatePitch函數傳遞給更新程序?

我在哪裏錯了?

+1

是否允許使用lambdas?使用'auto callback = [pOscillator](自動&語音,雙d){返回pOscillator-> ModulatePitch(語音,d); };'爲我工作。一般的經驗法則是當你可以使用lambdas時避免'std :: bind'。 – Maikel

+1

你有沒有考慮用lambdas替換'std :: bind'? – nwp

+1

使用'callback'的顯式類型將修復它。 'std :: function callback = ...' 但是我不能準確地說明爲什麼:) – pergy

回答

0

正如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)沒有被外部綁定調用。