纯虚函数重载和具有多重继承的协变返回类型

时间:2012-11-12 20:19:38

标签: c++ inheritance virtual covariant

我必须修改我之前的问题。对于多次吸入创建的协变返回类型是否有任何限制?

下面的代码提出了问题。如果我们从IDFPin取消对IDFOutputPin类吸入的注释,当我们尝试从Source类型的对象通过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;
}

1 个答案:

答案 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;
}

如果你有C ++ 11,你甚至可以使用get virt-specifier来装饰除override之外的所有内容。