2012-11-12 49 views
1

我必須修改我以前的問題。使用多次吸入創建協變回報類型是否有任何限制?純虛函數重載和多重進氣協同返回類型

下面的代碼提出了這個問題。如果我們從IDFP中取消類IDFOutputPin吸入的註釋,那麼當我們嘗試通過源類型的對象的IDFSourceNode接口獲取IDFOutputPin時,整個代碼會中斷。問題爲什麼會發生這種情況?我剛開始使用模板和這樣的mixins,所以也許有一些限制,或者它可能是編譯器的錯誤 - VS2010?謝謝你提供任何幫助:)

class PinBase {}; 
class Pin : public PinBase {}; 
class OutputPin : public Pin {}; 
class ExtOutputPin : public OutputPin {}; 
class IDFPin {}; 
class IDFOutputPin : /*public IDFPin,*/ public ExtOutputPin {}; // <---- when we uncomment this line part our covariant return type is created through multiple inharitance and the code breaks - question WHY? 
class CustomDFPin : public IDFOutputPin {}; 

class Node {}; 
class IDFNode : public virtual Node {}; 

class ISourceNode : public virtual Node 
{ 
public: 
    virtual OutputPin * get(int idx) = 0; 
}; 

class IDFSourceNode : public virtual IDFNode, public virtual ISourceNode 
{ 
public: 
    virtual IDFOutputPin * get(int idx) = 0; 
}; 

template<class Pin, class Node> 
class NodeImpl 
{ 
public: 
    typedef std::vector<Pin*> Pins; 

public: 

    void addPin(Pin * pin) 
    { 
     pins_.push_back(pin); 
    } 

    void removePin(Pin * pin) 
    { 
     std::remove(pins_.begin(), pins_.end(), pin); 
    } 

    Pin * pin(int idx) { return pins_[idx]; } 
    const Pin * pin(int idx) const { return pins_[idx]; } 

private: 
    Pins pins_; 
}; 

template<class OPin = Pin, class Interface = ISourceNode> 
class SourceNode : public virtual Interface 
{ 
protected: 

    void addPin(OPin * pin) 
    { 
     pins_.addPin(pin); 
    } 

public: 
    virtual OPin * get(int idx) 
    { 
     return pins_.pin(idx); 
    } 

private: 
    NodeImpl<OPin, SourceNode<OPin, Interface>> pins_; 
}; 

template<class OPin = DFPin, class Interface = IDFSourceNode> 
class DFSourceNode : public SourceNode<OPin, Interface> 
{ 

}; 

class Source : public DFSourceNode<CustomDFPin> 
{ 
public: 
    Source() 
    { 
     addPin(new CustomDFPin()); 
    } 
}; 



int main(int argc, char **argv) 
{ 
    Source * tmp = new Source(); 
    IDFSourceNode * tmpB = tmp; 
    CustomDFPin * pin = tmp->get(0); 
    IDFOutputPin * pinB = tmpB->get(0); //this call here calls pure virtual function if I am not wrong, exception is thrown when IDFOutputPin is created through multpile inharitance 

    return 0; 
} 

回答

2

我不能重現你的問題。下面的代碼工作正常,我似乎做你想要什麼:

struct A { }; 
struct B : A { }; 

struct Foo 
{ 
    virtual A * get() = 0; 
}; 

struct Bar : Foo 
{ 
    virtual B * get() = 0; 
}; 

struct Zip : Bar 
{ 
    //virtual A * get() { return nullptr; } // Error, as expected 
    virtual B * get() { return nullptr; } 
}; 

int main() 
{ 
    Zip x; 
} 

你甚至可以裝飾所有,但第一getoverride的virt-符,如果你有C++ 11。