2014-04-18 62 views
3
class animal { 
protected: 
    animal() {} 
    void eat(int x) {} 
}; 


class human 
    : private animal 
{ 
public: 
    typedef animal base_type; 
    using base_type::eat; 
}; 

class stomach { 
public: 
    stomach(std::function<void(int)> feed) {} 
}; 

class lady 
    : public human 
{ 
public: 
    typedef lady  this_type; 
    typedef human  base_type; 

    lady() 
     : base_type() 
     , m_Stomach(std::bind(&base_type::eat, this, std::placeholders::_1)) 
    { 
    } 

private: 
    stomach m_Stomach; 
}; 

如果客戶端代碼寫下來:如何在這種情況下std :: bind基類的方法?

lady gaga; 

編譯器抱怨std::bind(&base_type::eat, ...)錯誤C2064:術語不計算爲服用2個參數功能。

我已經發現,如果該類女士被修改爲:

class lady 
    : public human 
{ 
public: 
    typedef lady  this_type; 
    typedef human  base_type; 

    lady() 
     : base_type() 
     , m_Stomach(std::bind(&this_type::help_eat, this, std::placeholders::_1)) 
    { 
    } 

private: 
    void help_eat(int x) 
    { 
     base_type::eat(x); 
    } 
    stomach m_Stomach; 
}; 

有了一個幫助功能,編譯器會std::bind好。但代碼重複。

如果改變std::bind以拉姆達m_Stomach([&](int x){ base_type::eat(x); }),這也可以被編譯我也發現了。

我的問題是沒有在這種情況下使用std::bind更好的辦法?如果不是,我可能會考慮lambda。

回答

2

您的問題是animal私人基類的human並因此傳遞(並存儲)this(這是lady*類型的)不能被用來從animal調用該方法。你可以解決它使之成爲公共基礎或通過添加一個方法來human

animal* animal_ptr() { return this; } 

後來綁定:

std::bind(&base_type::eat, animal_ptr(), std::placeholders::_1) 

Live example

+0

很抱歉,但[實時示例](http://coliru.stacked-crooked.com/a/86aa3493784bdb9a)不能被編譯爲礦(VS2012)。我想念什麼? – cbel

+0

@cbel:我不使用VS/Windows,對不起。什麼是你得到確切的錯誤信息? –

+0

消息是一樣的,這是**錯誤C2064:術語不計算爲一個函數採取2個參數** – cbel

0

的動物是私人的基類人力和雖然using聲明使得功能可吃不改變功能的簽名void (animal::*)(int)

從7.3.3使用聲明

對於重載解析的目的,這是 通過使用聲明引入派生類的功能將被視爲 ,就像它們是成員派生類。特別地, 隱含該參數應被視爲好像它是一個指向 派生類而不是對基類。 這對 的功能的類型沒有影響,並且在所有其他方面的功能 保持基類的一個成員。

因此,結合(指功能型)導致錯誤‘animal’ is an inaccessible base of ‘lady’(克++)。

您可以通過使用lambda m_Stomach([this](int x) { this->eat(x); }), 來替代void eat(int x) { base_type::eat(x); }中的人類使用聲明或僅按照您的方式進行修復。

+0

恐怕作者感到困惑的是他用VS編譯器得到的不同錯誤,而不是這裏考慮的錯誤。你在這裏討論的問題已經被討論過了,例如http://stackoverflow.com/questions/19340190/c-boostbind-says-inaccessible -base-class – Ixanezis

+0

@Ixanezis我認爲錯誤C2064是明顯的誤導 –