我必须修改我之前的问题。使用多重继承创建协变返回类型是否有任何限制?
下面的代码提出了问题。如果我们取消注释从 IDFPin 继承的类 IDFOutputPin,当我们尝试通过 IDFSourceNode 接口从 Source 类型的对象获取 IDFOutputPin 时,整个代码都会中断。质疑为什么会这样?我刚刚开始使用模板和这样的mixin,所以也许有一些限制,或者可能是编译器错误 - 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 multiple inheritance
return 0;
}